jQuery in Action
36
CHAPTER 2
Creating the wrapped element set
The syntax of the
index()
command is as follows:
Now, rather than obtaining elements, how would you go about adjusting the set
of elements that are wrapped?
of elements that are wrapped?
2.3.3 Slicing and dicing the wrapped element set
Once we have a wrapped element set, we may want to augment that set by adding
to it or by reducing the set to a subset of the originally matched elements. jQuery
gives us a large collection of methods to manage the set of wrapped elements.
First, let's look at adding elements to a wrapped set.
to it or by reducing the set to a subset of the originally matched elements. jQuery
gives us a large collection of methods to manage the set of wrapped elements.
First, let's look at adding elements to a wrapped set.
Adding more elements to the wrapped set
Often, we may find ourselves in a situation where we want to add more elements
to an existing wrapped set. This capability is most useful when we want to add
more elements after applying some command to the original set. Remember,
jQuery chaining makes it possible to perform an enormous amount of work in a
single statement.
to an existing wrapped set. This capability is most useful when we want to add
more elements after applying some command to the original set. Remember,
jQuery chaining makes it possible to perform an enormous amount of work in a
single statement.
But first, let's examine a simple situation. Let's say that we want to match all
<img>
elements that have either an
alt
or a
title
attribute. The powerful jQuery
selectors allow us to express this as a single selector, such as
$('img[alt],img[title]')
But to illustrate the operation of the
add()
method, we could match the same set
of elements with
$('img[alt]').add('img[title]')
Using the
add()
method in this fashion allows us to chain a bunch of selectors
together into an or relationship, creating the union of the elements that satisfy
both of the selectors. Methods such as
both of the selectors. Methods such as
add()
can also be useful in place of selectors
Command syntax: index
index(element)
Finds the passed element in the wrapped set and returns its ordinal index within the set. If
the element isn't resident in the set, the value -1 is returned.
the element isn't resident in the set, the value -1 is returned.
Parameters
element
(Element) A reference to the element whose ordinal value is to be determined.
Returns
The ordinal value of the passed element within the wrapped set or -1 if not found.
The ordinal value of the passed element within the wrapped set or -1 if not found.