最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Want to set li innerHTML of ul - Stack Overflow

programmeradmin8浏览0评论

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. What is the proper way to do it?

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. What is the proper way to do it?

Share Improve this question edited Jul 8, 2015 at 2:41 alex 490k204 gold badges889 silver badges991 bronze badges asked May 27, 2011 at 0:35 rachrach 6916 gold badges16 silver badges20 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 15

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/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)

  1. 暂无评论