Appendix A. jQuery Primer

A lot of libraries have been developed to make the DOM easier to work with, but few have the popularity and praise of jQuery. And for good reason: jQuery’s API is excellent and the library is lightweight and namespaced, so it shouldn’t conflict with anything else you’re using. What’s more, jQuery is easily extendable; a whole host of plug-ins have been developed, from JavaScript validation to progress bars.

jQuery is namespaced behind the jQuery variable, which is aliased with a dollar sign ($). Unlike libraries such as Prototype, jQuery doesn’t extend any native JavaScript objects, largely to avoid conflicts with other libraries.

The other important thing to understand about jQuery is selectors. If you’re familiar with CSS, selectors will be second nature to you. All of jQuery’s instance methods are performed on selectors, so rather than iterating over elements, you can just use a selector to collect them. Any functions called on the jQuery selector will be executed on every element selected.

To demonstrate this, let me show you an example of adding a class name selected to all the elements with the class foo. The first example will be in pure JavaScript, and the second will use jQuery:

// Pure JavaScript example
var elements = document.getElementsByClassName("foo");
for (var i=0; i < elements.length; i++) {
  elements[i].className += " selected";

// jQuery example

So, you can see how jQuery’s selectors API greatly reduces the ...

Get JavaScript Web Applications now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.