jQuery in Action
Managing the wrapped element set
39
As if that weren't flexible enough, the
add()
method not only allows us to add
existing elements to the wrapped set, we can also use it to add new elements by
passing it a string containing
passing it a string containing
HTML
markup. Consider
$('p').add('<div>Hi there!</div>')
This fragment creates a wrapped set of all
<p>
elements in the document, and
then creates a new
<div>
, and adds it to the wrapped set. Note that doing so only
adds the new element to the wrapped set; no action has been taken in this state-
ment to add the new element to the
ment to add the new element to the
DOM
. We might then use the jQuery
append()
method (patience, we'll be talking about such methods soon enough) to
append the elements we selected, as well as the newly created
HTML
, to some
part of the
DOM
.
Augmenting the wrapped set with
add()
is easy and powerful, but now let's
look at the jQuery methods that let us remove elements from a wrapped set.
Honing the contents of the wrapped set
We saw that it's a simple matter in jQuery to create wrapped sets from multiple
selectors chained together with the
selectors chained together with the
add()
method to form an or relationship. It's
also possible to chain selectors together to form an except relationship by employ-
ing the
ing the
not()
method. This is similar to the
:not
selector filter we discussed ear-
lier, but can be employed in a similar fashion to the
add()
method to remove
elements from the wrapped set anywhere within a jQuery chain of commands.
Let's say that we want to select all
<img>
elements in a page that sport a
title
attribute except for those that contain the text puppy in the
title
attribute value.
We could come up with a single selector that expresses this condition (namely
img[title]:not([title*=puppy])
), but for the sake of illustration, let's pretend
that we forgot about the
:not
filter. By using the
not()
method, which removes
any elements from a wrapped set that match the passed selector expression, we
can express an except type of relationship. To perform the described match, we
can write
can express an except type of relationship. To perform the described match, we
can write
$('img[title]').not('[title*=puppy]')
Type this expression into the Wrapped Set Lab page, and execute it. You'll see
that only the tan puppy image is selected. The black puppy, which is included in
the original wrapped set because it possesses a
that only the tan puppy image is selected. The black puppy, which is included in
the original wrapped set because it possesses a
title
attribute, is removed by the
not()
invocation because its
title
contains the text puppy.
Note that the selectors we can pass to the
not()
method are limited to filter
expressions that omit any element reference (allowing it to imply all element
types). If we had passed the more explicit selector
types). If we had passed the more explicit selector
img[title*=puppy]
to the
not()