jQuery wrapper function and DOM methods

The jQuery's wrapper function features many interesting possibilities that should not be overlooked. The most underused feature of the $() alias is its ability accept an element reference obtained through normal DOM methods, such as getElementById(). This feature turns out to be very useful when we're working in a mixed environment or when we want to exploit the faster performance of built-in DOM methods. For example, in jQuery you can write this:

var test = document.getElementById('test');
$(test).text('Test');

As you can see, we've passed the reference to the element with ID test to the jQuery's wrapper function and then used a normal jQuery's method. What's more, this feature works also with other DOM core methods:

var li = document.getElementsByTagName('li');
  
  $(li).each(function() {
  
  
    alert($(this).text());
  
  });

So, what are the use cases? You can use this feature when you have to work with other libraries that return object and element references using DOM core methods or when you want to speed up a little bit your script performance. Remember that DOM core methods are implemented in the DOM engine of a web browser usually in C/C++. For that reason, they are much, much faster than any possible jQuery's implementation.

Leave a Reply

Note: Only a member of this blog may post a comment.