Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How specific should a selector be?

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?

like image 480
Milaan Avatar asked Dec 28 '22 16:12

Milaan


2 Answers

For this example $('.target') is the fastest. JQuery has figured out traversal algorithms ;)

Proof: http://jsperf.com/jquery-selector-speed-tests

like image 118
AlienWebguy Avatar answered Jan 06 '23 04:01

AlienWebguy


  • Id's need no extra descriptors. #id is better than div#id.
  • Sizzle usually works right-to-left (apparently when there's an id context on the left it searches that first), so it's better to be more specific on the right (so that fewer results remain and less secondary checks are run). However with modern browsers implementations of 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.

like image 32
davin Avatar answered Jan 06 '23 05:01

davin