I need to pick up list items from an list, and then perform operations like adding event handlers on them. I can think of two ways of doing this.
HTML:
<ul id="list">
<li id="listItem-0"> first item </li>
<li id="listItem-1"> second item </li>
<li id="listItem-2"> third item </li>
</ul>
Using the IDs-
for(i=0;i<3;i++) { document.getElementById("listItem-"+i).addEventListener("click",foo,false); }
Using childNodes property-
for(i=0;i<3;i++) { document.getElementById("list").childNodes[i] .addEventListener("click",foo,false); }
The reason i'm using the first approach is that in the function foo, if I want the index at which the item is located in the list, i can do it by splitting the id -
function foo()
{
tempArr = this.id.split('-');
index = tempArr[tempArr.length-1]; // the last element in the array
}
I can't think of a way of doing it by using the second method, that is, without using the id naming scheme.
The questions:
- How do I get the index using the second method or any better method
- Are there some very bad affects of following the first method ?