All the jQuery's architecture is based on the concept of a wrapped set, that is, a chain of jQuery's selectors and methods starting with the '$' sign. Although this is really useful for chaining together methods and routines in a compact way, sometimes it's preferable to use DOM methods and properties instead. Why? Basically, DOM methods and properties are usually implemented in C/C++, which is considerably faster than jQuery's implementation. To use DOM methods and properties in jQuery you have to move away from the wrapped set. For example, the following code won't work:
$('#test').getElementsByTagName('p'); // you get undefined
This is due to the fact that you're still inside the jQuery's wrapped set. To get the desired result you have to write:
$('#test')[0].getElementsByTagName('p'); // you get a NodeList of p elements
There's also another way: using the jQuery's get()
method, like so:
$('#test p').get(); // you get a NodeList of p elements
To summarize: both $(element)[0]
and $(elements).get()
allow us to exit from the wrapped set. But there's also another case: the difference between the $(this)
and this
notations. Example:
$('#test p').each(function() { alert($(this).attr('class')); // inside the wrapped set alert(this.getAttribute('class')); // outside the wrapped set });
If you use the this
keyword wrapped by the '$' sign, you're actually working inside the jQuery's wrapped set. Instead, if you use it without the '$' sign, you're outside the jQuery's wrapped set and you can use DOM methods and properties.