简体   繁体   中英

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 the ul`. 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?

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>";
}

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