RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


An Introduction to jQuery, Part 1 : Page 4

jQuery is a small JavaScript library that makes development of HTML-based client JavaScript drastically easier.


The Wrapped Set

The result of $("#gdEntries>tbody>tr:even") is a jQuery wrapped set object, which is an array-like structure that has a length property and an array containing all the matched elements. You can reference the DOM elements in the wrapped set directly:

   var res = $("#gdEntries>tbody>tr:even");
   var len = res.length; // match count. 0 = no matches
   var el = res[0];      // first element
   el = res.get(0);      // same but 'official' syntax
The jQuery constructor always returns an object result, so even if the selector finds no matches it returns an object. You can check the .length property to determine whether the selection returned matches.

After obtaining a set of matches you can iterate through them manually using a for loop or use the wrapped set function .each() to iterate over the list. What's nice about .each() is that it assigns the this pointer to the selected DOM element; in other words, you can do this:

   $("#gdEntries tbody tr:even").each( 
      function(index) {
         alert(this.id + " at index: " + index);    

Wrapped Set Functions

Manual iteration is useful at times, but more commonly you'll use one or more of jQuery's 100+ operational functions on wrapped set elements. The jQuery selector applies both the .addClass() and .css() functions you saw above against all the elements that it matches to those you created with the jQuery() or $() function—in this case each of the rows you selected. You can find all the jQuery functions on the API reference page, or if you're into terse lookup sheets you can check out this printable jQuery cheat sheet.

Function Chaining

jQuery lets you use a fluent interface for most function calls, which means that you can chain many jQuery function calls together in a single command. You've already seen some examples:

   $("#gdEntries tbody tr")
       .css("border","solid 1px lightgrey");
This syntax chaining works because most jQuery functions return a matched set as a result. For example, .addClass and .css both return the original matched set they acted upon. Other functions such as .not and .filter modify the original matched set and return a new matched set. There's also an .end() function that you can use to remove any filters and return to the original matched set that you specified at the beginning of the chain.

Chaining is a great way to keep code compact—but it's optional. If you prefer, you can write more traditional code, for example:

   var matches = $("#gdEntries>tbody>tr");
Chained statements can sometimes be difficult to debug, because you get a single result value at the end. In contrast, using explicit methods lets you see changes after each step, which can be useful for debugging. For I often break up commands for debugging and chain them back together after they're fully debugged.

Still, not all jQuery functions can be chained. Functions such as .val(), .text(), and .html() return string values; .width() and .height() return numbers; and .position() returns a position object. If you study the jQuery function list it should be pretty clear what the result types of most functions are. Typically, functions that you would expect to return a void result return a matched set—all others return values or data.

Event Handling

Event handling is one of jQuery's nicest aspects because it makes the process easy and consistent across browsers. jQuery provides the high level .bind() and .unbind() functions that generically attach and detach event handlers to and from matched set elements. That makes it easy to attach events to many objects at once—such as the click handler attached to the rows in the example shown earlier. In addition, most common events such as click, keystroke, and mouse events have corresponding dedicated handler functions: .click(), .mousedown(), change(), and .keydown(). jQuery event handlers take a function as a parameter. jQuery tracks these handlers so that it can unbind them later. Coding doesn't get any easier than this. There's even an option to name event handlers uniquely so that you can remove them in a consistent way:

   $("#gdEntries tr")
      .bind("click.MyHandler",function(e) {...});
   $("#gdEntries tr")
The extra name following the event name in the preceding example lets you specifically identify an individual event handler. In contrast, the default behavior would remove all event handlers for an event that were assigned with .bind() or the various convenience handlers such as .click().

jQuery also includes:

  • .one(): This fires an event exactly once, and then disconnects the handler.
  • .toggle(): This toggles between alternating clicks
  • .trigger(): This can trigger events on elements through code.
jQuery's common model for event handlers includes these features:

  • The this pointer always equals the element the event fired on.
  • jQuery always passes an event object as a parameter.
  • The event object is cross-browser normalized.

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date