jQuery in Action
Selecting elements for manipulation
23
This matches any
<form>
element that has an explicit
method
attribute.
To match a specific attribute value, we use something like
input[type=text]
This selector matches all input elements with a type of
text
.
We've already seen the "match attribute at beginning" selector in action.
Here's another:
div[title^=my]
This selects all
<div>
elements with
title
attributes whose value begins with
my
.
What about an "attribute ends with" selector? Coming right up:
a[href$=.pdf]
This is a useful selector for locating all links that reference
PDF
files.
And there's a selector for locating elements whose attributes contain arbitrary
strings anywhere in the attribute value:
a[href*=jquery.com]
As we would expect, this selector matches all
<a>
elements that reference the
jQuery site.
Beyond attributes, we'll sometimes want to select an element only if it contains
some other element. In the previous list example, suppose we want to apply some
behavior to list elements containing links. jQuery supports this kind of selection
with the container selector:
behavior to list elements containing links. jQuery supports this kind of selection
with the container selector:
li:has(a)
This selector matches all
<li>
elements that contain an
<a>
element. Note that
this is not the same as a selector of
li
a
, which matches all
<a>
elements contained
within
<li>
elements. Use the Selectors Lab page to convince yourself of the dif-
ference between these two forms.
Table 2.1 shows the
CSS
selectors that we can use with jQuery.
Be aware that only a single level of nesting is supported. Although it's possible
to nest one level, such as
foo:not(bar:has(baz))
additional levels of nesting, such as
foo:not(bar:has(baz:eq(2)))
aren't supported.