I am trying to add another <a> element after <a id='link1'>
<html>
<head>
<script src="js/jquery-1.6.4.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var myHTML = "<div id='test'>";
myHTML += "<span><a id='link1'>link 1</a></span>";
$("a#link1").after("<a id='link2'>link 2</a>");
myHTML += "</div>";
$("div#insertHere").html(myHTML);
});
</script>
</head>
<body>
<div id="insertHere">
</div>
</body>
</html>
The output of the above should be
<body>
<div id="insertHere">
<div id="test">
<span>
<a id="link1">link 1</a>
<a id="link2">link 2</a>
</span>
</div>
</div>
</body>
You are trying to query elements you haven’t added to the DOM yet.
When you do
$("a#link1")it does not retrieve any element because the HTML you “generated” before is not in the DOM yet, it’s still just text in your variablemyHTML.Generate all the markup and apply it at once:
If you need to bind events (or else) to the elements you are adding, you can use the dom manipualtion API from jquery:
Further reading: