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 ...
Get JavaScript Web Applications now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.