开发者

Is there any method/way in javascript to add a child node to list element dynamically?

If I have an unordered list like

<ul id="list">
<li>Helo World-1</li>
<li>Helo World-2</li>
<li>Helo World-3</li>
</ul>

I want to add a sublist item to it dynamically. Is there any method in javascript to do that. How could I do it. edit I need an item at next level, i.e. a sub list of Helo World that I m开发者_运维百科entioned in OP too, something like as under. One more issue here is that I need the items to be a permanent part of my code.

 <ul id="list">
    <li>Helo World-1</li>
    <li>Helo World-2</li>
    <li>Helo World-3</li>
       <ul>
         <li>One</li>
         <li>Two</li>
      </ul>
 </ul> 


Using pure DOM methods:

var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode("Your list item text"));

To add the list item to the end of the list:

ul.appendChild(li);

To insert the list item between existing list items (note you'd have to give the existing list item an id in this example):

ul.insertBefore(li, document.getElementById("list_item_id"));

Update

If you want to add a nested list, you'll need to add it to a list item rather than directly inside the list in order for it to be valid:

var lis = ul.getElementsByTagName("li");

var lastLi = lis[lis.length - 1];

var nestedUl = document.createElement("ul");
var nestedLi = nestedUl.appendChild(document.createElement("li"));
nestedLi.appendChild(document.createTextNode("One"));

lastLi.appendChild(nestedUl);


$('<li>...</li>').appendTo($('#list')); /* in jquery */

otherwise straight js

var mylist = document.getElementById('list');
mylist.appendChild(document.createElement('li'));

Note: if you need to set also text

var mylist = document.getElementById('list');
var newli  = document.createElement('li');

newli.innerHTML('Helo World ' + mylist.getElementsByTagName('li').length + 1);
mylist.appendChild(newli);


I've created a sample in jsfiddle

var el = document.getElementById("list");

var li = document.createElement("li");
li.innerHTML = "item";

el.appendChild(li);

You can go through the w3schools html dom reference to see how we can manipulate the html elements using javascript.

But I think the cleaner way will be to use a third party library like jQuery which will allow a much easier way to manipulate the dom.

ex: If use jQuery this will be as easy as

$("<li>...</li>").appendTo("#list")

EDIT: Based on your edit you can try this,

var ul = document.getElementById("list");
ul.children[2].innerHTML = "<ul><li>sub 1</li><li>sub 2</li><li>sub 3</li></ul>";

This will get the 3rd <li> of the <ul> and add a sublist to it


AFAIK, there is no equivalent HTML DOM object for list. Anyway you can use the innerHTML:

var list = document.getElementById("list");
var item = "<li>New Item</li>";
list.innerHTML += item;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜