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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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

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

If you’re using a traversal method, you may want to keep the original matched set of elements as well.<br />

The .<strong>and</strong>Self() method provides this ability <strong>by</strong> allowing the original set to be recalled <strong>and</strong> appended to<br />

the new set.<br />

For instance, to match all paragraph elements <strong>and</strong> then find child spans, use the following code:<br />

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

This returns the spans in the document, but you’ve lost the paragraphs:<br />

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

[ span, span.foo ]<br />

To keep the paragraphs <strong>and</strong> match the spans, add a call to .<strong>and</strong>Self() to the end of the code:<br />

$("p").find("span").<strong>and</strong>Self();<br />

This results in the desired output:<br />

>>> $("p").find("span").<strong>and</strong>Self();<br />

[ p, p.foo, p, span, p#bar, span.foo ]<br />

.contents()<br />

The .contents() method works similarly to the .children() method, except .contents() returns text<br />

nodes as well, which are simply the character data contained within an element (the actual text displayed<br />

<strong>by</strong> an element). 1<br />

To find all contents of the span with class foo, use the following:<br />

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

This results in the following output:<br />

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

[ ]<br />

1 http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-1312295772<br />

35

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

Saved successfully!

Ooh no, something went wrong!