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?
You need to access the child
lielements of theul. JavaScript and the DOM API can’t automagically do that for you.You could also use
getElementsByTagName('li')but it will get all descendentlielements, and it seems you want only the direct descendants.You could also avoid
innerHTMLif you want.innerHTMLcan 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.