jQuery in Action
6
CHAPTER 1
Introducing jQuery
such as waiting until the page is loaded before performing page operations, have
been silently solved for us.
been silently solved for us.
Should we find that the library needs a bit more juice, its developers have built
in a simple but powerful method for extending its functionality. Many new jQuery
programmers find themselves putting this versatility into practice by extending
jQuery on their first day.
programmers find themselves putting this versatility into practice by extending
jQuery on their first day.
But first, let's look at how we can leverage our
CSS
knowledge to produce pow-
erful, yet terse, code.
1.3.1 The jQuery wrapper
When
CSS
was introduced to web technologies in order to separate design from
content, a way was needed to refer to groups of page elements from external
style sheets. The method developed was through the use of selectors, which con-
cisely represent elements based upon their attributes or position within the
style sheets. The method developed was through the use of selectors, which con-
cisely represent elements based upon their attributes or position within the
HTML
document.
For example, the selector
p a
refers to the group of all links (
<a>
elements) that are nested inside a
<p>
element.
jQuery makes use of the same selectors, supporting not only the common selec-
tors currently used in
tors currently used in
CSS
, but also the more powerful ones not yet fully imple-
mented by most browsers. The
nth-child
selector from the zebra-striping code we
examined earlier is a good example of a more powerful selector defined in
CSS3
.
To collect a group of elements, we use the simple syntax
$(selector)
or
jQuery(selector)
Although you may find the
$()
notation strange at first, most jQuery users
quickly become fond of its brevity.
For example, to retrieve the group of links nested inside a
<p>
element, we use
the following
$("p a")
The
$()
function (an alias for the
jQuery()
function) returns a special Java-
Script object containing an array of the
DOM
elements that match the selector.
This object possesses a large number of useful predefined methods that can act
on the group of elements.
on the group of elements.