jQuery in Action
Managing the wrapped element set
41
matched elements as the
this
value for the invocation. The function uses a regu-
lar expression to determine if the element content matches the described pattern
(a sequence of one or more digits), returning
(a sequence of one or more digits), returning
false
if not. Every element whose
filter function invocation returns
false
is removed from the wrapped set.
Again, bring up the Wrapped Set Lab, type the previous expression in, and exe-
cute it. You will see that the table cells for the Invented column are the only
cute it. You will see that the table cells for the Invented column are the only
<td>
elements that end up being selected.
The
filter()
method can also be used with a passed selector expression that
conforms to the same constraints that we described earlier for the
not()
method,
namely, filter selectors with an implied element type. When used in this manner,
it operates in the inverse manner than the corresponding
it operates in the inverse manner than the corresponding
not()
method, remov-
ing any elements that do not match the passed selector. This isn't a powerful
method, as it's usually easier to use a more restrictive selector in the first place,
but it can be useful within a chain of jQuery commands. Consider, for example,
method, as it's usually easier to use a more restrictive selector in the first place,
but it can be useful within a chain of jQuery commands. Consider, for example,
$('img').addClass('seeThrough').filter('[title*=dog]')
.addClass('thickBorder')
This chained statement selects all images and applies the
seeThrough
class to
them and then reduces the set to only those image elements whose
title
attribute
contains the string
dog
before applying another class named
thickBorder
. The
result is that all the images end up semi-transparent, but only the tan dog gets the
thick border treatment.
thick border treatment.
The
not()
and
filter()
methods give us powerful means to adjust a set of
wrapped elements on the fly, based on just about any criteria regarding aspects
Command syntax: filter
filter(expression)
Filters out elements from the wrapped set using a passed selector expression, or a filtering
function.
function.
Parameters
expression
(String|Function) Specifies a jQuery selector used to remove all elements
that do not match from the wrapped set, or a function that makes the
that do not match from the wrapped set, or a function that makes the
filtering decision. This function is invoked for each element in the set,
with the current element set as the function context for that invocation.
Any element that returns an invocation of false is removed from
the set.
Returns
The wrapped set.
The wrapped set.