When I was looking at the jQuery code source, I became interested in Sizzle-js, which is a CSS selector engine library that jQuery uses for selecting DOM elements. So, my question is why jQuery includes an entire library for just selecting DOM elements? What features introduce Sizzle that let's jQuery uses it internally?
In order to answer on this I do some researches on Sizzle and his features, the main function of Sizzle is Sizzle(selector)
, this function returns an array-like object that contains some methods that allow you to operate on the DOM elements you've isolated, and this is very helpful actually if your application touched the DOM frequently. But, in my opinion, this isn't worth to include a 20KB of code, I know that Sizzle covered also the old browser versions that don't support the Document.querySelectorAll
function, but I'm still not convinced!
Actually, you can do what Sizzle do (Simulate the concept) in few lines of code, I've written a very simple example based on querySelectorAll
:
var Select = function(selector) {
if (typeof selector !== 'string') throw 'selector must be of type string';
var client = function() {
var eles = document.querySelectorAll(selector), i = eles.length;
this.length = eles.length;
while(i--) {
this[i] = eles[i];
}
};
client.prototype = Array.prototype;
return new client();
};
console.log(Sizzle('div').includes(document.querySelector('div'))); // true
console.log(Select('div').includes(document.querySelector('div'))); // true
var divs = Select('div');
divs.forEach(function(div) {
div.textContent = 'Changed!!';
});
So why jQuery still uses Sizzle? the document.querySelectorAll
and document.querySelector
are now available in modern browsers, why jQuery still depends on Sizzle on this?
Note: There is an old question that is similar to this one, however, I'm not satisfied with the answers since it focuses more on What is Sizzle JS, and what can do ?, rather than why jQuery uses Sizzle?.
I hope my question was clear and sorry for my bad English, thanks.
jQuery's selector syntax includes a number of extensions to CSS selectors, such as :input
and :selected
. You can see the list here. These extensions are implemented in Sizzle.
jQuery will use querySelectorAll()
if it can, but reverts to Sizzle if necessary.