02.06.2013 Views

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

30<br />

CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS<br />

[ span.foo ]<br />

.closest()<br />

The .closest() method is an easy way to find elements up the DOM tree, which is the nesting order of<br />

elements (a DOM tree relationship in your example is the span within a paragraph within the body<br />

element).<br />

For example, to find the closest paragraph to the span with class foo, run the following code snippet<br />

in the console:<br />

$("span.foo").closest("p");<br />

This outputs the following:<br />

>>> $("span.foo").closest("p");<br />

[ p#bar ]<br />

.find()<br />

Similar to the .children() method, the .find() method matches descendants of elements within the<br />

current set. The main difference between .find() <strong>and</strong> .children() is that .children() only checks one<br />

level down in the DOM tree, whereas .find() doesn’t care how deep the matched elements are.<br />

To demonstrate, select the body tag <strong>and</strong> then find any contained span elements using the following:<br />

$("body").find("span");<br />

This results in both spans being returned:<br />

>>> $("body").find("span");<br />

[ span, span.foo ]<br />

However, if you were to try the same thing using .children(), an empty result set is returned:<br />

>>> $("body").children("span");<br />

[ ]<br />

.next(), .nextAll(), <strong>and</strong> .nextUntil()<br />

A trio of useful methods for finding the next sibling elements in a set is provided in .next(), .nextAll(),<br />

<strong>and</strong> .nextUntil().<br />

The .next() method will find the next sibling element in the set for each of the elements in the<br />

original result set. To select a paragraph with class foo <strong>and</strong> then traverse to the next sibling element,<br />

execute the following code in the console:

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

Saved successfully!

Ooh no, something went wrong!