jQuery: selector chaining details

jQuery allows us to move in and out the selector chaining by using the get() method. This method has the ability to turn a jQuery object into a normal DOM object. By using this method we're actually moving out the selector chaining. To move back in the selector chaining, we need to use the jQuery wrapper shortcut $(). Let's make an example. Suppose that we have a basic unordered list like this:

<ul id="test">

We want to iterate over each list item using a traditional for loop. First, we need to turn all the items into simple DOM objects:

var li = $('#test li').get();

Now li is a normal DOM NodeList. We can use our loop as follows:

var i, len = li.length;
for(i = 0; i < len; i += 1) {
  // do something with each item

Since we're currently outside the jQuery selector chaining, we'd like to move back to it. We can accomplish this task using $():

for(i = 0; i < len; i += 1) {

  var $li = $(li[i]);
  // code continues  

Now we're again within the selector chaining and we can use a normal jQuery method on each item:

// code continues

       fontSize: '1.5em'
     }, 2000, function() {
         fontSize: '1em'
       }, 2000);

You can see a test below.


Live test

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

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