When creating an ordered list of elements, I can think of three reasonable ways to access one by index:
Give it a unique id with a number at the end and use string manipulation:
<ol>
<li id="item-0"></li>
<li id="item-1"></li>
<li id="item-2"></li>
</ol>
...
for(var i = 0; i < 3; i++) {
$('#item-' + i).doWhatever();
}
give them the same class and use the eq selector:
<ol>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
</ol>
...
for(var i = 0; i < 3; i++) {
$('.item').eq(i).doWhatever();
}
or give them the same class and use the nth-child selector:
<ol>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
</ol>
...
for(var i = 1; i <= 3; i++) {
$('.item:nth-child(' + i + ')').doWhatever();
}
What are the advantages and disadvantages of each? Are there other, better ways?
I’ve added a fourth test case to your perf test: http://jsperf.com/item1-vs-item-eq-1/2
Considering your points in order:
getElementByIdandchildNodesThe main thing to consider, I think, is that all of your methods involve repeatedly querying the DOM as you’re iterating through the list. If you’re only ever accessing a single element, that’s not a big deal, but if you’re going to be working through the entire list, then only making a single query is going to make a big difference performance-wise.
EDIT Out of curiosity, I updated my case again not to use jQuery for locating the list at all, instead just using the barebones DOM API as I’d mentioned above.
Even with the changes Sandor made after pointing out my dumb mistake, there’s a noticeable performance impact. With that in mind, I’d say it’s mostly going to come down to your specific use case and how you weigh speed versus versatility in locating your list items.