Chainability (The Magic of jQuery)

Friday, February 06, 2009 by ASP.NET AJAX Team | Comments 0

This article is taken from How jQuery Works.

 

jQuery uses an interesting concept called a "Builder" to make its code short and simple. The Builder pattern is an object-oriented programming design pattern that has been gaining popularity.

In a nutshell: Every method within jQuery returns the query object itself, allowing you to 'chain' upon it, for example:

$("a")
   .filter(".clickme")
     .click(function(){
       alert("You are now leaving the site.");
     })
   .end()
   .filter(".hideme")
     .click(function(){
       $(this).hide();
       return false;
     })
   .end();
 

Which would work against the following HTML:

<a href="http://google.com/" class="clickme">I give a message when you leave</a>
 <a href="http://yahoo.com/" class="hideme">Click me to hide!</a>
 <a href="http://microsoft.com">I'm a normal link</a>

Methods that modify the jQuery selection and can be undone with end(), are the following:

  • add(),
  • children(),
  • eq(),
  • filter(),
  • find(),
  • gt(),
  • lt(),
  • next(),
  • not(),
  • parent(),
  • parents() and
  • siblings().

Please check the Traversing API documentation for details of these methods.

 

Peter

Add comment

  1. Formatting options
       
     
     
     
     
       
  2. (optional, emails won't be shown on public pages)
  3. (optional)