Reputation: 5197
I can't for the life of me work out why this is happening.
Here is a fiddle of what I'm seeing:
https://jsfiddle.net/258xsLsp/
Here is the sample HTML:
<ul>
<li id="test1">Magazines</li>
<li id="test2">Topics</li>
</ul>
...and the JS:
$(document).ready(function() {
$("<ul>").appendTo("#test1");
$("<li>foo</li>").appendTo("#test1");
$("</ul>").appendTo("#test1");
});
...and the output I'm looking for:
<ul>
<li id="test1" data-cat-id="5817">Magazines
<ul>
<li>foo</li>
</ul>
</li>
<li id="test2" data-cat-id="2000000">Topics</li>
</ul>
...yet what I get, is:
<ul>
<li id="test1" data-cat-id="5817">Magazines<ul></ul><li>foo</li></li>
<li id="test2" data-cat-id="2000000">Topics</li>
</ul>
I must be missing something stupid! I've tried both append() and appentTo(), and neither seem to want to work.
Upvotes: 1
Views: 42
Reputation: 920
.append()
and not .appendTo()
You are appending them both to #test1
which will put them one after the other. To next the list item, you can store your ul
in a variable so you can then append to it.
$(document).ready(function() {
var topNode= $('<ul></ul>'); //create and store the ul (not we have not inserted it into the dom yet)
topNode.append('<li>foo</li>'); //append the inner list item to our stored ul
$('#test1').append(topNode); //append the whole thing to the first list item (into the dom)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li id="test1" data-cat-id="5817">Magazines</li>
<li id="test2" data-cat-id="2000000">Topics</li>
</ul>
Upvotes: 0
Reputation: 255
Or you can go this way:
$("<ul>").append("<li>foo</li>").appendTo('#test1')
Upvotes: 2
Reputation: 20740
You are appending <li>foo</li>
to #test1
. You should append it to #test1 ul
like following.
$(document).ready(function () {
$("<ul/>").appendTo("#test1");
$("<li>foo</li>").appendTo("#test1 ul"); // change here
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li id="test1">Magazines</li>
<li id="test2">Topics</li>
</ul>
Upvotes: 1