简体   繁体   中英

add ul to a li element in an existing ul

i need to add a sub ul to a existing list inside a ul.

i have a existing ul like this

 <li id="0" class="dropdown"> <a href="#">Articles</a> </li>
<li id="1" class="dropdown"> <a href="#">Global</a> </li>
<li id="2" class="dropdown open"> <a href="#" class="dropdown-toggle" data-   toggle="dropdown">Commodities <b class="caret"></b></a></li>
<li id="3" class="dropdown"> <a href="#">Mergers</a> </li>
<li id="4" class="dropdown"> <a href="#">Dividend</a> </li>
<li id="5" class="dropdown"> <a href="#">Tech</a> </li></ul>

this list is created dynamically, i need to append a ul to the third li, ie,

<li id="2" class="dropdown open"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Commodities <b class="caret"></b></a>
<ul>
  something.....

how is this possible??

Firstly don't define the id starting with number.

Then, you can use append like this:

$('li#third').append('ul');

Or, like this:

$('<ul />').appendTo('li#third');

Go thorough the api for more information.

This is solely JavaScript solution:

function add_ul()
{
    var li = document.getElementById("li");
    var ul = document.createElement("ul");
    ul.appendChild(document.createTextNode("Another UL Element"));
    li.appendChild(ul);
}

You can use .append() or appendTo()

 $('.open').append("<ul id='subul'>sub</ul>");

if sub ul element already exists in dom then:

 $('#subul').appendTo('.open');

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM