Skip to Main Content
JavaScript Web Applications
book

JavaScript Web Applications

by Alex MacCaw
August 2011
Intermediate to advanced content levelIntermediate to advanced
276 pages
6h 37m
English
O'Reilly Media, Inc.
Content preview from JavaScript Web Applications

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
$(".foo").addClass("selected");

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

JavaScript Application Design

JavaScript Application Design

Nicolas Bevacqua
JavaScript: Best Practice

JavaScript: Best Practice

James Kolce, Moritz Kroger, Ivan Curic, Samier Saeed, Jeff Mott, M. David Green, Craig Buckler

Publisher Resources

ISBN: 9781449308216Errata PageSupplemental Content