jQuery in Action
40
CHAPTER 2
Creating the wrapped element set
method instead, we would not get the expected result because element selectors
are not supported.
are not supported.
As with
add()
, the
not()
method can also be used to remove individual elements
from the wrapped set by passing a reference to an element or an array of element
references. The latter is interesting and powerful because, remember, any jQuery
wrapped set can be used as an array of element references.
references. The latter is interesting and powerful because, remember, any jQuery
wrapped set can be used as an array of element references.
At times, we may want to filter the wrapped set in ways that are difficult or
impossible to express with a selector expression. In such cases, we may need to
resort to programmatic filtering of the wrapped set items. We could iterate
through all the elements of the set and use the
resort to programmatic filtering of the wrapped set items. We could iterate
through all the elements of the set and use the
not(element)
method to remove
the specific elements that do not meet our selection criteria. But the jQuery team
didn't want us to have to resort to doing all that work on our own and so have
defined the
didn't want us to have to resort to doing all that work on our own and so have
defined the
filter()
method.
The
filter()
method, when passed a function, invokes that function for each
wrapped element and removes any element whose function invocation returns
the value
the value
false
. Each invocation has access to the current wrapped element via
the function context (
this
) in the body of the filtering function.
For example, let's say that, for some reason, we want to create a wrapped set of
all
<td>
elements that contain a numeric value. As powerful as the jQuery selector
expressions are, such a requirement is impossible to express using them. For such
situations, the
situations, the
filter()
method can be employed, as follows:
$('td').filter(function(){return this.innerHTML.match(/^\d+$/)})
This jQuery expression creates a wrapped set of all
<td>
elements and then
invokes the function passed to the
filter()
method for each, with the current
Command syntax: not
not(expression)
Removes elements from the matched set according to the value of the expression parame-
ter. If the parameter is a jQuery filter selector, any matching elements are removed. If an ele-
ment reference is passed, that element is removed from the set.
ter. If the parameter is a jQuery filter selector, any matching elements are removed. If an ele-
ment reference is passed, that element is removed from the set.
Parameters
expression
(String|Element|Array) A jQuery filter expression, element reference, or
array of element references defining what is to be removed from the
wrapped set.
array of element references defining what is to be removed from the
wrapped set.
Returns
The wrapped set.
The wrapped set.