LEARNING JAVASCRIPT - Trang 303

class if it does). You can also manipulate style directly with the

css

method. We’ll also

introduce the

:even

and

:odd

selectors, which allow you to select every other ele‐

ment. For example, if we wanted to make every other paragraph red, we could do the

following:

$

(

'p:odd'

).

css

(

'color'

,

'red'

);

Inside a jQuery chain, it’s sometimes desirable to select a subset of the matched ele‐

ments. We’ve already seen

eq

, which allows us to reduce the jQuery object to a single

element, but we can also use

filter

,

not

, and

find

to modify the selected elements.

filter

reduces the set to elements that match the specified selector. For example, we

can use

filter

in a chain to make every other paragraph red after we’ve modified

each paragraph:

$

(

'p'

)

.

after

(

'<hr>'

)

.

append

(

'<sup>*</sup>'

)

.

filter

(

':odd'

)

.

css

(

'color'

,

'red'

);

not

is essentially the inverse of

filter

. For example, if we want to add an

<hr>

after

every paragraph, and then indent any paragraph that doesn’t have the class

high

light

:

$

(

'p'

)

.

after

(

'<hr>'

)

.

not

(

'.highlight'

)

.

css

(

'margin-left'

,

'20px'

);

Finally,

find

returns the set of descendant elements that match the given query (as

opposed to

filter

, which filters the existing set). For example, if we wanted to add

an

<hr>

before every paragraph and then increase the font size of elements with the

class

code

(which, in our example, are descendants of the paragraphs):

$

(

'p'

)

.

before

(

'<hr>'

)

.

find

(

'.code'

)

.

css

(

'font-size'

,

'30px'

);

Unwrapping jQuery Objects

If we need to “unwrap” a jQuery object (get access to the underlying DOM elements),

we can do so with the

get

method. To get the second paragraph DOM element:

const

para2

=

$

(

'p'

).

get

(

1

);

// second <p> (zero-based indices)

To get an array containing all paragraph DOM elements:

const

paras

=

$

(

'p'

).

get

();

// array of all <p> elements

Unwrapping jQuery Objects | 279