pav
9/12/2013 - 12:37 PM

First, last, and eq all reduce a selection of one or more elements down to just one. But sometimes, we will want to filter it down, not nec

First, last, and eq all reduce a selection of one or more elements down to just one.

But sometimes, we will want to filter it down, not necessarily to just one element, but to zero, one, or more elements based on a certain condition.

jQuery has a function for this: .filter(). It can be passed a selector, a function, an element, or a jQuery object, and behaves slightly differently for each type of argument. To filter for li elements in a jQuery selection $listOfElements, you would use $listOfElements.filter("li");.

//selecting the divs and adding the h1s to the selection
$headingsAndDivs = $('div').add('h1');

//filter it to only elements that have the class 'selectMe'
$filtered = $headingsAndDivs.filter('.selectMe');