09.02.2015 Views

DOM Traversal Methods - MarkMail

DOM Traversal Methods - MarkMail

DOM Traversal Methods - MarkMail

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Selector Expressions<br />

Multiple Elements: E,F,G<br />

Selects all elements matched by selector expressions E, F, or G.<br />

Examples<br />

1. $('code, em, strong'): selects all elements matched by or or<br />

<br />

2. $('p strong, .myclass'): selects all elements matched by that<br />

are descendants of an element matched by as well as all elements that<br />

have a class of myclass<br />

Description<br />

This comma (,) combinator is an efficient way to select disparate elements. An<br />

alternative to this combinator is the .add() method described in Chapter 3.<br />

Nth Child (:nth-child(n))<br />

All elements that are the n th child of their parent.<br />

Examples<br />

1. $('li:nth-child(2)'): selects all elements matched by that are the<br />

second child of their parent<br />

2. $('p:nth-child(5)'): selects all elements matched by that are the fifth<br />

child of their parent<br />

Description<br />

Because jQuery's implementation of :nth-child(n) is strictly derived from the CSS<br />

specification, the value of n is 1-based, meaning that the counting starts at 1. For all<br />

other selector expressions, however, jQuery follows JavaScript's "0-based" counting.<br />

Therefore, given a single containing two s, $('li:nth-child(1)') selects<br />

the first while $('li:nth(1)') selects the second.<br />

Because the two look so similar, the :nth-child(n) pseudo-class is easily confused<br />

with :nth(n), even though, as we have just seen, the two can result in dramatically<br />

different matched elements. With :nth-child(n), all children are counted,<br />

regardless of what they are, and the specified element is selected only if it matches<br />

the selector attached to the pseudo-class. With :nth(n) only the selector attached<br />

to the pseudo-class is counted, not limited to children of any other element, and the<br />

nth one is selected. To demonstrate this distinction, let's examine the results of a few<br />

selector expressions given the following HTML:<br />

<br />

<br />

[ 22 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!