I have a parent element with a real lot of child elements (1000s). I am looking for the fastest possible way to get a handle to the last child element. The options I've found are:
$('.parent .child').last()
and
$('.parent .child:last')
Any opinions on which one is reliably faster across browsers?
EDIT
I wrote a test in jsfiddle to measure this out and it turns out the difference is pretty much negligible. Though .last() was performing better, the difference is negligible. So i think even with the :last selector, it is actually getting the whole list of elements and then returning the last element? Unbelievable.
Fiddle: http://jsfiddle.net/techfoobar/GFb9f/8/
Many modern browsers support document.querySelectorAll()
, so $('.parent .child').last()
should be faster, as the selector string can be passed as is, and then the last matched item popped off.
In the latter, the :last
is not a standard pseudo selector, and Sizzle has to start chunking the selector string to start matching.
Overall though, I would use what you believe is the most readable. To begin optimising this, first ensure that your application has performance issues and you have identified this selector as the bottleneck.
You have to see this performance test!
UPDATE: There are already good answers on this related question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With