02.06.2013 Views

jQuery Cookbook - Cdn.oreilly.com - O'Reilly

jQuery Cookbook - Cdn.oreilly.com - O'Reilly

jQuery Cookbook - Cdn.oreilly.com - O'Reilly

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

link<br />

link<br />

link<br />

link<br />

<br />

<br />

//alerts 4 left in the set<br />

alert(<strong>jQuery</strong>('a').filter('.external').length + ' external links');<br />

<br />

<br />

<br />

The HTML page in the code example just shown contains a web page with 10 <br />

elements. Those links that are external links are given a class name of external. Using<br />

the <strong>jQuery</strong> function, we select all elements on the page. Then, using the filter method,<br />

all those elements that do not have a class attribute value of external are removed<br />

from the original set. Once the initial set of DOM elements are altered using the<br />

filter() method, I invoke the length property, which will tell me how many elements<br />

are now in my new set after the filter has been applied.<br />

Discussion<br />

It’s also possible to send the filter() method a function that can be used to filter the<br />

wrapped set. Our previous code example, which passes the filter() method a string<br />

expression, can be changed to use a function instead:<br />

alert(<br />

<strong>jQuery</strong>('a')<br />

.filter(function(index){ return $(this).hasClass('external');})<br />

.length + ' external links'<br />

);<br />

Notice that I am now passing the filter() method an anonymous function. This function<br />

is called with a context equal to the current element. That means when I use<br />

$(this) within the function, I am actually referring to each DOM element in the wrapper<br />

set. Within the function, I am checking each element in the wrapper set to see<br />

whether the element has a class value (hasClass()) of external. If it does, Boolean true,<br />

then keep the element in the set, and if it doesn’t (false), then remove the element from<br />

the set. Another way to look at this is if the function returns false, then the element is<br />

removed. If the function returns any other data value besides false, then the element<br />

will remain in the wrapper set.<br />

You may have noticed that I have passed the function a parameter named index that I<br />

am not using. This parameter, if needed, can be used to refer numerically to the index<br />

of the element in the <strong>jQuery</strong> wrapper set.<br />

1.5 Filtering a Wrapper Set of DOM Elements | 17

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

Saved successfully!

Ooh no, something went wrong!