Home > Articles > Web Development > Ajax and JavaScript

  • Print
  • + Share This
Like this article? We recommend jQuery Chaining

jQuery Chaining

The ability to use high-level selectors instead of climbing up and down the DOM tree searching for the desired objects is tremendously useful, but several JavaScript libraries offer the same functionality; for example, the latest jQuery release has replaced its selector-matching code with the Sizzle engine (which has been released to the Dojo Foundation). The feature that really makes jQuery shine is its chaining capability: Every jQuery method returns the same set on which it was called (unless the method is meant to modify the set, such as the find or filter method), allowing you to chain numerous methods without ever having to store the intermediate results.

Suppose you want to find all external links in your web page, add a CSS class to them (to change their color), attach an onclick event (to open the destination in a new window), and append an image to the text (because the CSS background image of an inline object is not always rendered correctly in Internet Explorer). You can do all this with a single JavaScript statement—hopefully, spread across multiple lines to increase readability:

  .append('<img src="/images/externalLink.png" />');
  • + Share This
  • 🔖 Save To Your Account