I have a general question about jQuery. Lets say I have the following code:
<div id="container">
<ul>
<li>1</li>
<li class="target">2</li>
<li>3</li>
</ul>
</div>
What is the best, and fastest?, way to select the target
element?
$('div#container ul li.target')
or
$('#container .target')
or
$('li.target')
or is this even faster:
$('.target')
I want to know, what is the best way in achieving this? You can say the more specific the better, but too specific will slow the process down, I guess. Also the class
method is "slower", but that difference isn't that big anymore, or am I wrong?
For this example $('.target')
is the fastest. JQuery has figured out traversal algorithms ;)
Proof: http://jsperf.com/jquery-selector-speed-tests
#id
is better than div#id
.querySelectorAll
may not hold to that, so really it's difficult to tell.On the whole it's difficult to tell, and for the most part changes will be micro-optimisations. How many selections are you doing anyway that it makes such a difference? More importantly, if your execution is slow, have you profiled it and clarified where the bottleneck is? If not, you're probably squeezing very hard and are not going to get much lemon juice out of this one.
Finally, you have to realise as many jsperfs or other benchmarks that people throw at you, it is inconclusive to the general case. It's all very case specific. Maybe your DOM is simple, maybe in the future it will be more complicated. You need to test your own case. Another answer links to a solution whose conclusion I totally disagree with. There, the DOM has 4 elements, in a real-world case, it might have 4000 which means all bets are off.
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