HTML5 and CSS3, Second Edition

(singke) #1
our pages faster. Using Google’s content-delivery network has an additional
benefit—since other sites link to the jQuery library at Google, our visitors
may already have the library cached by their browsers. As you probably
already know, browsers use a file’s full URL to decide whether it has a cached
copy. If you plan to work with jQuery on a laptop or on a computer without
constant Internet access, you’ll want to link to a local copy instead.

A2.2 jQuery Basics


Once you’ve loaded the jQuery library on your page, you can start working
with elements. jQuery has a function called jQuery(), which lets us fetch ele-
ments using CSS selectors and wrap them in jQuery objects so we can
manipulate those elements.

There’s a short version of the jQuery() function, $();, and that’s what we use in
this book. Throughout this book, I refer to this as “the jQuery function.” Here’s
how it works:

If you wanted to find the h1 tag on a page, you’d use the following:


jqueryprimer/simple_selection.html
$("h1");

If you wanted to find all of the <h1> tags on the page, you’d use the exact
same thing. If you were looking for all elements with the class of important,
you’d do this:

jqueryprimer/simple_selection.html
$(".important");

Look at that again. The only difference between it and the previous examples
is the CSS selector we used. If we were looking for the element with the id of
header, we’d simply do

varheader= $("#header");

And if we wanted to find all links within the sidebar, we’d use the appropriate
selector for that, which would be $("#sidebara").

The jQuery function returns a jQuery object, which is a special JavaScript
object containing an array of the DOM elements that match the selector. This
object has many predefined methods we can use to manipulate the elements
we selected. Let’s take a look at a few of those in detail.

A2.3 Methods to Modify Content


We use several jQuery methods to modify our HTML content as we work
through the projects in this book.

Appendix 2. jQuery Primer • 264


Download from Wow! eBook <www.wowebook.com> report erratum • discuss

Free download pdf