JQuery: understanding how selectors are implemented
Until now, we’ve been looking at how we can build JQuery objects (which wrap one or more HTML nodes) through the use of several selectors and filters and the jQuery method (though in most samples, we’ve been using the $ alias). Currently, this method looks like this:
function( selector, context ) {
return new jQuery.fn.init( selector, context );
},
The fn field of the JQuery object is just an alias for the JS prototype property you use for extending JS objects. As you can see, the init method is the responsible for interpreting the current request and for returning the JQuery object that will be used. If you’ve been following along, then you’ve probably noticed that we’ve also used the $ for setting up the ready event. Besides these two usages, there’s still two more options: you can use the $ for creating new HTML elements from a string(we’ll see how in future posts) or you can wrap an existing DOM node by passing a reference to that element to the jQuery method. In this post, I’ll only concentrate on the code used for implementing the selector syntax.
As you can see, the function receives two parameters: a selector and a context. Until now, we’ve only been passing the first parameter and haven’t really paid any attention to the context parameter. The truth is that you can use that second parameter to limit the search of the item specified on the selector string to the set of items contained in the context parameter. In practice, passing a valid context parameter would be equivalent to calling $(context).find(selector) in order to get the context child elements that match a specific context.
Understanding the expression is an important step that starts with using regular expressions. Since we’re only concentrating on the scenario where we’re passing a string with a valid selector, that means that JQuery starts by identifying the passed string. The easiest path is when it detects a simple ID. when that happens, JQuery ends up calling the traditional document.getElementById for getting the element that will be wrapped by the JQuery object.
All other cases end up being processed by the find method (in practice, the platform ends up creating a JQuery object that wraps the document node so that it can call the JQuery find method and pass it the current selector). The most important work is performed by the querySelectorAll method, when the browser supports it. When that doesn’t happen, Sizzle is used for doing the hard work.
Notice that the end result is a JQuery object with an array with an array that points to the references that matched the selector you’ve passed, as you can see from the following picture:
I guess that sums it up. In future posts we’ll keep looking at JQuery basics. Keep tuned for more.