jQuery in Action
44
CHAPTER 2
Creating the wrapped element set
All of the methods in table 2.4, with the exception of
contents()
, accept a param-
eter containing a string that can be used to filter the results.
2.3.5 Even more ways to use a wrapped set
As if all that were not enough, there are still a few more tricks that jQuery has up
its sleeve to let us define our collections of wrapped objects.
its sleeve to let us define our collections of wrapped objects.
The
find()
method lets us search through an existing wrapped set and returns
a new set that contains all elements that match a passed selector expression. For
example, given a wrapped set in variable
example, given a wrapped set in variable
wrappedSet
, we can get another
wrapped set of all citations (
<cite>
elements) within paragraphs with
wrappedSet.find('p cite')
Note that if this were all to occur in a single statement, we could also accomplish
this by passing a context parameter to a jQuery selector:
this by passing a context parameter to a jQuery selector:
$('p cite',wrappedSet)
Like many other jQuery wrapped set methods, the
find()
method's power comes
when it's used within a jQuery chain of operations.
In addition to finding elements in a wrapped set that match a selector, jQuery
also provides a method to find elements that contain a specified string. The
also provides a method to find elements that contain a specified string. The
con-
tains()
method will return a new wrapped set that consists of all elements that
contain the passed string anywhere within its body content. Consider
$('p').contains('Lorem ipsum')
This expression yields a wrapped set containing all paragraphs that contain the
text Lorem ipsum. Note that the string test is applied to all aspects of the body
text Lorem ipsum. Note that the string test is applied to all aspects of the body
Command syntax: find
find(selector)
Returns a new wrapped set containing all elements of the original set that match the passed
selector expression.
selector expression.
Parameters
selector
(String) A jQuery selector that elements must match to become part of the
returned set.
returned set.
Returns
The newly created wrapped set.
The newly created wrapped set.