Filtering Selections and Arrays (^) ❘ 147
padding: 10px;
background: yellow;
width: 250px;
}
ul li {
padding: 3px;
}
h4 {
margin: 10px 0 ;
}
li.rubberSoulJohnAndPaul {
background: lightblue;
}
The following script demonstrates how jQuery’s filter() method can use a callback function to
reduce items present in a selection:
$(document).ready(
function()
{
$('ul#rubberSoul li')
.filter(
function()
{
return $(this).hasClass('John') || $(this).hasClass('Paul');
}
)
.addClass('rubberSoulJohnAndPaul');
}
);
In the preceding script, the filter() method iterates over each item present in the original selection.
It looks at each individual
John or a class name of Paul; if either class name is present, the callback function returns true, indi-
cating that the item should be kept in the selection. Each item kept in the selection then receives a
class name of rubberSoulJohnAndPaul. Figure 5-5 shows a screenshot of this example in Safari. Each
song written primarily by John or Paul has a lightblue background.
Filtering an Array
As indicated previously, arrays are fi ltered using a different method called grep(), which can be
called only directly, which is to say, you may call it only as $.grep() or jQuery.grep(). Wrapping
an array in the dollar sign method and then calling grep() doesn’t work for this utility method. The
grep() method would typically be used to directly fi lter some arbitrary array of items in code, rather
than a selection from the DOM because the filter() method already exists explicitly for fi ltering
selections. The following example, Example 5-6, demonstrates how grep() is used to fi lter arrays by
creating an array of items from a selection; this is done simply to demonstrate how grep() works:
<!DOCTYPE HTML>
<html lang='en'>
<head>
<meta http-equiv='X-UA-Compatible' content='IE=Edge' />
<meta charset='utf-8' />