jQuery in Action
38
CHAPTER 2
Creating the wrapped element set
We can see that five of the six images (all but the coffee pot) were added to the
wrapped set. (The red outline may be a bit hard to see in the print version of this
book with grayscale figures.)
wrapped set. (The red outline may be a bit hard to see in the print version of this
book with grayscale figures.)
Now let's take a look at a more realistic use of the
add()
method. Let's say that
we want to apply a thick border to all
<img>
elements with
alt
attributes, and then
apply a level of transparency to all
<img>
elements with either
alt
or
title
attributes. The comma operator (,) of
CSS
selectors won't help us with this one
because we want to apply an operation to a wrapped set and then add more ele-
ments to it. We could easily accomplish this with multiple statements, but it would
be more efficient and elegant to use the power of jQuery chaining to accomplish
the task in a single statement, such as
ments to it. We could easily accomplish this with multiple statements, but it would
be more efficient and elegant to use the power of jQuery chaining to accomplish
the task in a single statement, such as
$('img[alt]').addClass('thickBorder').add('img[title]')
.addClass('seeThrough')
In this statement, we create a wrapped set of all
<img>
elements with
alt
attributes, apply a predefined class that applies a thick border, add the
<img>
ele-
ments that have
title
attributes, and finally apply a class that applies transpar-
ency to the newly augmented set.
Enter this statement into the Wrapped Set Lab page (which has predefined the
named classes), and view the results as shown in figure 2.8.
In these results, we can see that the flower images (those with
alt
) have thick
borders, and all images but the coffee pot (the only one with neither an
alt
nor a
title
) are faded as a result of applying an opacity rule.
The
add()
method can also be used to add elements to an existing wrapped set
given references to those elements. Passing an element reference, or an array of
element references, to the
element references, to the
add()
method adds the elements to the wrapped set. If
we assume that we have an element reference in a variable named
someElement
, it
could be added to the set of all images containing an
alt
property with
$('img[alt]').add(someElement)
Figure 2.8
jQuery chaining allows us to
perform complex operations
in a single statement, as
seen by these results.
perform complex operations
in a single statement, as
seen by these results.