开发者

Want to set li innerHTML of ul

I'm writing a javascript function where I get a ul object from my HTML and want to set the text of one of the li elements in theul`. I'm doing:

list = document.getElementById('list_name');

Then I want to access the ith li element of list using a loop. I have:

for (i = 0; i < 5; i++) {
    list[i].innerHTML = "<a>text</a>"; 
}

but this is not working. Wha开发者_C百科t is the proper way to do it?


You need to access the child li elements of the ul. JavaScript and the DOM API can't automagically do that for you.

var list = document.getElementById('list_name'),
    items = list.childNodes;

for (var i = 0, length = childNodes.length; i < length; i++)
{
    if (items[i].nodeType != 1) {
       continue;
    }
    items[i].innerHTML = "<a>text</a>"; 
}

You could also use getElementsByTagName('li') but it will get all descendent li elements, and it seems you want only the direct descendants.

You could also avoid innerHTML if you want.

var a = document.createElement('a'),
    text = document.createTextNode('text');

a.appendChild(text);
items[i].appendChild(a);

innerHTML can cause issues, such as lost event handlers and the performance issue of serialising and re-parsing the HTML structure. This should be negligible in your example, however.


jQuery Sample code, although the others work:

$("#list_name li").text("<a href=''>text</a>");

Its much more succinct with jQuery


You can try the following

var el = document.createElement("li"),
    content = document.createTextNode("My sample text"),
    myUl = document.getElementById("ulOne");

el.appendChild(content);
el.id = "bar";

myUl.appendChild(el);

Here's the demo: http://jsfiddle.net/x32j00h5/


I prefer a aproach using getElemenetByTagName, if somehow you get a extra node like a script tag or a span you will have problems. A guess this code will help you:

var list = document.getElementById("mylist");
var items = list.getElementsByTagName("li");
for(var i = 0, size = items.length; i< size; i++){
    items[i].innerHTML = "<a href='#'>LINK</a>";
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜