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 ?
You can avoid adding event handlers to each list item by adding a single event handler to the containing element (the unordered list) and leveraging the concept of event bubbling. In this single event handler, you can use properties of the event object to determine what was clicked.
It appears that you are wanting to map data in an array to list items. While parsing out an array index out of the list item id would work, another approach would be to store a ‘key’ value on the list item as an expando, and use javascript object properties to do a lookup for your data.
Partial Example:
As far as bad effects of the first technique you showed, one bad effect is that with many list items you end up with many event handlers being defined, which at some point would have an impact on performance.
Also note that you may be unintentionally creating a global var in your loops by omitting the var keyword for ‘i’.