Suppose I have a huge list of elements with a structure like:
<div class="item">
<div class="header"></div>
<div class="body"></div>
<div class="meta"></div>
<div class="..."></div>
...
</div><!-- .item -->
I’ve already found an element and now I have to find, let’s say, a ‘.body’. What code will work faster:
$(el).find('.body')
or
$(el).find('.body').eq(0)
In other words, will jQuery stop on the first found element or will it loop through all the elements first and only then it will return an element with a chosen index?
Your second example will always be slower, because it only calls an additional method on a jQuery object that contains all the elements matching
.body.The fastest way to get the first matching element is probably the :first selector:
You could also spare one method call by using the
contextargument to $(), but benchmarks reveal that’s actually slower: