Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selector optimization

Tags:

Be specific on the right-hand side of your selector, and less specific on the left.

// unoptimized
$('div.data .gonzalez');

// optimized
$('.data td.gonzalez');

Quote Source

  1. Could someone explain why the less specific left is faster as a CSS selector?

  2. Is this a Sizzle thing or does the same apply for document.querySelectorAll ?

  3. Are there any speed gains using "similarly optimised" CSS selectors in CSS files?

like image 751
Raynos Avatar asked May 17 '11 09:05

Raynos


1 Answers

jQuery's Sizzle Engine parse selectors from right to left, so it's true. There are exceptions though, for example when the first operand is an ID. Then the search will operate in the context of the element with this ID. That's a particularity of the Sizzle Engine, but I don't know how querySelectorForAll is implemented.

An example:

$('div.data .gonzalez');

Sizzle will get all the DOM elements with class gonzalez then check for each if an ancestor is a div tag with class data

like image 59
Grooveek Avatar answered Sep 28 '22 10:09

Grooveek