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.

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

To select the same paragraph as the preceding example <strong>by</strong> counting backward from the end of the<br />

result set, use the following code:<br />

$("p").eq(-3);<br />

This returns the same paragraph in the console:<br />

>>> $("p").eq(-3);<br />

[ p.foo ]<br />

.filter() <strong>and</strong> .not()<br />

To use a whole new selector within a set of elements, the .filter() method comes in h<strong>and</strong>y. It accepts<br />

any selector that can be used in the <strong>jQuery</strong> function, but it applies only to the subset of elements<br />

contained within the <strong>jQuery</strong> object.<br />

For instance, to select all paragraphs <strong>and</strong> then filter out all but the ones with class foo, you would<br />

use the following:<br />

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

The result in the console will read as follows:<br />

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

[ p.foo ]<br />

The inverse of .find() is .not(), which will return all elements from a result set that do not match<br />

the given selector. For instance, to select all paragraphs <strong>and</strong> then limit the selection to paragraphs that<br />

do not have the class foo, you would use the following:<br />

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

This results in the following:<br />

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

[ p, p, p#bar ]<br />

.first() <strong>and</strong> .last()<br />

The .first() <strong>and</strong> .last() methods work identically to .eq(0) <strong>and</strong> .eq(-1), respectively. To select the<br />

last paragraph from a set of all paragraphs on the page, use the following:<br />

$("p").last();<br />

This results in the following:<br />

27

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

Saved successfully!

Ooh no, something went wrong!