or
with class="note"
children of
or div.note
Note that the CSS and jQuery selector syntax use parentheses
for some of the filters in simple selectors, but they do not allow
parentheses to be used more generally for grouping. You cannot put a selector group or selector combination in parentheses
and treat it like a simple selector, for example:
(h1, h2, h3)+p
h1+p, h2+p, h3+p
// Not legal
// Write this instead
Selection Methods
In addition to the selector grammar supported by $(), jQuery
defines a number of selection methods. Most of the jQuery
methods we’ve seen so far in this chapter perform some action
on the selected elements. The selection methods are different:
they alter the set of selected elements by refining it, augmenting
it, or just using it as a starting point for a new selection.
This section describes these selection methods. You’ll notice
that many of the methods provide the same functionality as the
selector grammar itself.
The simplest way to refine a selection is by its position within
the selection. first() returns the jQuery object that contains
only the first selected element, and last() returns the jQuery
object that contains only the last element. More generally, the
Selection Methods | 95
eq() method returns a jQuery object that contains only the
single selected element at the specified index. (In jQuery 1.4,
negative indexes are allowed and count from the end of the
selection.) Note that these methods return a jQuery object with
a single element. This is different than regular array indexing,
which returns a single element with no jQuery object wrapped
around it:
var paras = $("p");
paras.first()
paras.last()
paras.eq(1)
paras.eq(-2)
paras[1]
//
//
//
//
//
Select only the first
tag
Select only the last
Select the second
Select the second to last
The second
tag, itself
The general method for refining a selection by position is
slice(). The jQuery slice() method works like the
Array.slice() method: it accepts a start and an end index (with
negative indexes measured from the end of the array), and returns a jQuery object that contains elements from the start index up to, but not including, the end index. If the end index is
omitted, the returned object includes all elements at or after
the start index:
$("p").slice(2,5)
$("div").slice(-3)
// The 3rd, 4th and 5th
tags
// The last three
tags
filter() is a general-purpose selection filtering method, and
you can invoke it in three different ways:
• If you pass a selector string to filter(), it returns a jQuery
object containing only those selected elements that also
match that selector.
• If you pass another jQuery object to filter(), it returns a
new jQuery object that contains the intersection of the
two jQuery objects. You can also pass an array of elements, or even a single document element, to filter().
• If you pass a predicate function to filter(), that function
is called for each matched element, and filter() returns
a jQuery object containing only those elements for which
the predicate returned true (or any truthy value). The
predicate function is called with the element as its this
96 | Chapter 8: Selectors and Selection Methods
value, and the element index as an argument. (See also
jQuery.grep() in Chapter 7.)
$("div").filter(".note")
// Like $("div.note")
$("div").filter($(".note"))
// Like $("div.note")
$("div").filter(function(i) { // Like $("div:even")
return i % 2 == 0
})
The not() method is just like filter() except that it inverts the
sense of the filter. If you pass a selector string to not(), it returns
a new jQuery object containing only the selected elements that
do not match the selector. If you pass a jQuery object or an
array of elements or a single element, not() returns all of the
selected elements except for those elements you’ve explicitly
excluded. If you pass a predicate function to not(), it is invoked
just as it is for filter(), but the returned jQuery object includes
only those elements for which the predicate returns false (or
a falsy value):
// All
tags except two special ones
$("div").not("#header, #footer");
In jQuery 1.4, the has() method is another way to refine a selection. If you pass a selector, it returns a new jQuery object
that contains only the selected elements that have a descendant
that matches the selector. If you pass a document element to
has(), it refines the selection to match only those elements that
are ancestors of the specified element:
$("p").has("a[href]")
// Paragraphs that include links
The add() method augments a selection rather than filtering or
refining it. You can invoke add() with any arguments (other
than a function) that you would pass to $(). add() returns the
originally selected elements, plus whatever elements would be
selected (or created) by the arguments if those arguments were
passed to $(). add() removes duplicate elements and sorts the
combined selection so that elements are in document order:
// Equivalent ways to select all
and
elements
$("div, p")
// Use a selector group
$("div").add("p")
// Pass a selector to add()
$("div").add($("p")) // Pass a jQuery object to add()
Selection Methods | 97
var paras = document.getElementsByTagName("p");
$("div").add(paras);
// Pass an array-like object
Using a Selection As Context
The filter(), add(), and not() methods described above perform set intersection, union, and subtraction operations on
independent selections. jQuery defines a number of other selection methods that use the current selection as the context.
For each selected element, these methods make a new selection
using the selected element as the context or starting point, and
then return a new jQuery object that contains the union of
those selections. As with the add() method, duplicates are removed and the elements are sorted so that they are in document
order.
The most general of this category of selection methods is
find(). It searches the descendants of each of the currently selected elements for elements that match the specified selector
string, and returns a new jQuery object that represents that
new set of matching descendants. Note that the newly selected
elements are not merged with the existing selection; they are
returned as a new set of elements. Note also that find() is not
the same as filter(), which simply narrows the currently selected set of elements without selecting new elements:
// find
tags inside
tags.
$("div").find("p")
Same as $("div p")
The other methods in this category return new jQuery objects
that represent the children, siblings, or parents of each of the
currently selected elements. Most accept an optional selector
string as an argument. With no selector, they return all appropriate children, siblings, or parents. With the selector, they filter the list to return only those that match.
The children() method returns the immediate child elements
of each selected element, filtering them with an optional
selector:
98 | Chapter 8: Selectors and Selection Methods
// Find all
tags that are direct children of the
// elements with ids "header" and "footer".
// Same as $("#header>span,#footer>span")
$("#header, #footer").children("span")
The contents() method is similar to children() but it returns
all child nodes, including text nodes, of each element. Also, if
any of the selected elements is an