jQuery API

.filter()

.filter( selector ) Returns: jQuery

Description: Reduce the set of matched elements to those that match the selector or pass the function's test.

  • version added: 1.0.filter( selector )

    selectorA string containing a selector expression to match the current set of elements against.

  • version added: 1.0.filter( function(index) )

    function(index)A function used as a test for each element in the set. this is the current DOM element.

  • version added: 1.4.filter( element )

    elementAn element to match the current set of elements against.

  • version added: 1.4.filter( jQuery object )

    jQuery objectAn existing jQuery object to match the current set of elements against.

Given a jQuery object that represents a set of DOM elements, the .filter() method constructs a new jQuery object from a subset of the matching elements. The supplied selector is tested against each element; all elements matching the selector will be included in the result.

Consider a page with a simple list on it:

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

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

The result of this call is a red background for items 1, 3, and 5, as they match the selector (recall that :even and :odd use 0-based indexing).

Using a Filter Function

The second form of this method allows us to filter elements against a function rather than a selector. For each element, if the function returns true (or a "truthy" value), the element will be included in the filtered set; otherwise, it will be excluded. Suppose we have a somewhat more involved 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 the list items, then filter them based on their contents:

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

This code will alter the first list item only, as it contains exactly one <strong> tag. Within the filter function, this refers to each DOM element in turn. The parameter passed to the function tells us the index of that DOM element within the set matched by the jQuery object.

We can also take advantage of the index passed through the function, which indicates the 0-based position of the element within the unfiltered set of matched elements:

$('li').filter(function(index) {
  return index % 3 == 2;
}).css('background-color', 'red');

This alteration to the code will cause the third and sixth list items to be highlighted, as it uses the modulus operator (%) to select every item with an index value that, when divided by 3, has a remainder of 2.

Examples:

Example: Change the color of all divs; then add a border to those with a "middle" class.

<!DOCTYPE html>
<html>
<head>
  <style>
  div { width:60px; height:60px; margin:5px; float:left;
        border:2px white solid;}
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div></div>

  <div class="middle"></div>
  <div class="middle"></div>
  <div class="middle"></div>
  <div class="middle"></div>

  <div></div>
<script>

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

</body>
</html>

Demo:

Example: Change the color of all divs; then add a border to the second one (index == 1) and the div with an id of "fourth."

<!DOCTYPE html>
<html>
<head>
  <style>
  div { width:60px; height:60px; margin:5px; float:left;
        border:3px white solid; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
  <div id="first"></div>
  <div id="second"></div>
  <div id="third"></div>

  <div id="fourth"></div>
  <div id="fifth"></div>
  <div id="sixth"></div>
<script>
    $("div").css("background", "#b4b0da")
            .filter(function (index) {
                  return index == 1 || $(this).attr("id") == "fourth";
                })
            .css("border", "3px double red");

</script>

</body>
</html>

Demo:

Example: Select all divs and filter the selection with a DOM element, keeping only the one with an id of "unique".

$("div").filter( document.getElementById("unique") )

Example: Select all divs and filter the selection with a jQuery object, keeping only the one with an id of "unique".


$("div").filter( $("#unique") )

Support and Contributions

Need help with .filter() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .filter()? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • Andrei

    What is the difference between filter() and find() ?

  • Anonymous

    I believe filter() only search in those elements that match the precondition. But find() search under (children) the precondition. For example:

    bye

    hello

    ("div").filter(".g") will select "d1"
    (from all "div" elements, select those with class "g")
    ("div").find(".g") will select "v2"
    (from all "div" elements select all children with class "g").

  • Adrian

    Problem:
    I have an Div with an auto-generated id:

    Contents
    the “id” will be changed on Reload to > allfriends{RANDOM_ID}.

    Can i select this div with jQuery?
    (“div”).find(“#allfriends*”) (example??)

  • Nigel

    Can you put a class on your div and use that as the selector instead?

    Or you could use the 'Attribute starts with' selector here: http://api.jquery.com/attribute-starts-with-sel…

  • anurag pal

    hi,
    i have miltiple div tag on page like below.
    <div>math</div><div>biology</div><div>chemistry</div>
    now i want to add add anothor div dynamically with value <div>chemistry</div> which was already added on the page .my problem is that i want to check the existing value on the page. that it is already added or not on the page.

  • Phanindra Kanna

    i have a problem to select dynamically the selected options
    for ex:
    <select >
    <option>1</option>
    <option selected=”selected>2</option>
    <option>3</option>
    <option>4</option>
    </select>
    <button>click</button>
    i am request u to solve my prob ,i..e,
    when i click the button ,the perticular option should select ,plz help me

  • http://darkliquid.co.uk Andrew Montgomery-Hurrell

    From an optimisation point of view, if you have a situation where you need to apply something to a set of elements, but also apply something to a subset of that set, is it quicker to select the superset, and then use filter to get the subset or would there be no difference from doing two separate finds (the later having the additional selectors to get only the subset)?

    I'm not sure how jQuery works internally, so I'm not clear on whether or not the selection engine goes over only the current set or just builds a new search using the current scope and the new filter information.

  • http://www.learningjquery.com/ Karl Swedberg

    I would bet that selecting the superset first and then filtering to get the subset would be faster/better because jQuery will filter only those elements contained in the current matched set of elements. But don't take my word for it; you can set up a performance test yourself over at http://jsperf.com/

  • http://twitter.com/The_Mighty_Zeus Jason Brown

    It's worth noting that .find() will find children, children's children, and all descendants. Whereas .children() works exactly the same way, but will only find children, not more distant descendants.

  • http://twitter.com/The_Mighty_Zeus Jason Brown

    I would recommend, as Nigel did, the “attribute starts with” selector. In your case it would look like $('div[id^=allfriends]')

  • http://vynce.myopenid.com/ Vynce

    Is there a reason you chose a different argument list for .filter() than the standard JS array method filter() ? Also, it seems (experimentally) that the argument list to filter is actually (index, element) not just (index). If this is true, please document it.

    .

  • Mozilla11

    find ids of images having perticular src

  • Oussama-010

    Nguni seeej