jQuery doorzoeken - filter() methode

Voorbeeld

Verander de kleur van alle div's en voeg een rand toe aan de klasse met de naam "middle":

$("div").css("background", "#c8ebcc")
  .filter(".middle")
  .css("border-color", "red");

Try it yourself

Definition and usage

The filter() method reduces the set of matched elements to those that match the specified selector.

Syntax

.filter(selector)
Parameter Description
selector String value, containing the selector expression to match the current element collection.

Detailed description

If a jQuery object representing a collection of DOM elements is given, the .filter() method will construct a new jQuery object containing the subset of elements that match. The selector used will test each element; all elements that match the selector will be included in the result.

Please consider the following page with a simple list:

<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li>list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
  <li>list item 6</li>
</ul>

We can apply this method to the collection of list items:

$('li').filter(':even').css('background-color', 'red');

Try it yourself

The result of this call is to set the background color of items 1, 3, and 5 to red, because they all match the selector (remember, :even and :odd both use 0-based index).

Using filter function

The second form of this method is to filter elements through a function rather than a selector. For each element, if the function returns true, the element will be included in the filtered set; otherwise, it will be excluded.

Please see the following slightly more complex HTML snippet:

<ul>
  <li><strong>list</strong> item 1 - one strong tag</li>
  <li><strong>list</strong> item <strong>2</strong>
   - two <span>strong tags</span></li>
  <li>list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
  <li>list item 6</li>
</ul>

we can select these list items and then filter them based on their content:

$('li').filter(function(index) {
  return $('strong', this).length == 1;
).css('background-color', 'red');