Can someone help adding to 'li' into 'ul'. not sure what im missing here. I have html in a variable
Below is the code snippet
var myhtml = "<div><ul></ul></div>"; var msg = "<li>some message</li>"; $(myhtml).find("ul").append(msg); $("#mycontainer").append(myhtml);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id=mycontainer>My Div</div>
You almost had it, but you forgot to append your list to the div. Just try doing it like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id=mycontainer>My Div</div>
<script>
var myhtml = "<div><ul></ul></div>";
var msg = "<li>some message</li>";
$(mycontainer).append($(myhtml).find("ul").append(msg))
</script>
Here's a JSBin with a working version.
This does the trick, but I'm sure there will be a neater way, you could fiddle with this a little more and make it more minimal and concise.
var div = "<div></div>"; var li = "<li>Some Message</li>"; var ul = $("<ul></ul>").append(li); var constructor = $(div).append(ul); $('#mycontainer').append(constructor);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id=mycontainer>My Div</div>
var myhtml = "<div><ul></ul></div>"; var msg = "<li>some message</li>"; $("#mycontainer").append(myhtml); $("#mycontainer").find("ul").append(msg);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="mycontainer">My Div</div>
The UL
doesn't exist yet therefore you can't append to it at that point. Change it around like so and it should work.
var myhtml = "<div><ul></ul></div>"; var msg = "<li>some message</li>"; $("#mycontainer").append(myhtml); $("#mycontainer div ul").append(msg);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id=mycontainer>My Div</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.