jQuery Cookbook - Cdn.oreilly.com - O'Reilly
jQuery Cookbook - Cdn.oreilly.com - O'Reilly
jQuery Cookbook - Cdn.oreilly.com - O'Reilly
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
These filters can also be used with regular CSS syntax. For example, selecting all text<br />
input elements plus all elements can be done in the following way:<br />
<strong>jQuery</strong>(':text, textarea');<br />
2.10 Selecting an Element with Specific Characteristics<br />
Problem<br />
You need to select an element based not only on its relationship to other elements or<br />
simple attribute values but also on varying characteristics such as programmatic states<br />
not expressible as selector expressions.<br />
Solution<br />
If you’re looking for an element with very specific characteristics, selector expressions<br />
may not be the best tool. Using <strong>jQuery</strong>’s DOM filtering method (filter()), you can<br />
select elements based on anything expressible within a function.<br />
The filter method in <strong>jQuery</strong> allows you to pass either a string (i.e., a selector expression)<br />
or a function. If you pass a function, then its return value will define whether certain<br />
elements are selected. The function you pass is run against every element in the current<br />
selection; every time the function returns false, the corresponding element is removed<br />
from the collection, and every time you return true, the corresponding element is not<br />
affected (i.e., it remains in the collection):<br />
<strong>jQuery</strong>('*').filter(function(){<br />
return !!<strong>jQuery</strong>(this).css('backgroundImage');<br />
});<br />
The preceding code selects all elements with a background image.<br />
The initial collection is of all elements (*); then the filter() method is called with a<br />
function. This function will return true when a backgroundImage is specified for the<br />
element in question. The !! that you see is a quick way of converting any type in Java-<br />
Script to its Boolean expression. Things that evaluate to false include an empty string,<br />
the number zero, the value undefined, the null type, and, of course, the false Boolean<br />
itself. If any of these things are returned from querying the backgroundImage, the function<br />
will return false, thus removing any elements without background images from<br />
the collection. Most of what I just said is not unique to <strong>jQuery</strong>; it’s just JavaScript<br />
fundamentals.<br />
In fact, the !! is not necessary because <strong>jQuery</strong> evaluates the return value into a Boolean<br />
itself, but keeping it there is still a good idea; anyone looking at your code can be<br />
absolutely sure of what you intended (it aids readability).<br />
2.10 Selecting an Element with Specific Characteristics | 47