The Difference Between .Find() And .Filter() Methods In jQuery

If you are new to jQuery, you may have confusion with the jQuery find() and filter() methods. The reason is both find() and filter() methods are very similar. But the way they work is different! The filter() method filters the elements from current set while the find() method searches child elements of selected element.

In short:

filter() - search in selected element set (collection filtering)
find() - search in the children elements (traversal filtering)

  Let’s say, we have HTML DOM like:

  • list item 1
  • list item 2
  • list item 3
  • list item 4
  • list item 5
  • list item 6
  • list item 7

Suppose we want to use filter() method to get all the “

  • ” elements having class “findme“.

    We can use filter() as follows:

    //Get all 'li' with class 'findme'
    var selectedElements = $('li').filter('.findme');

     But here find() will not work if we use the same way like: $(‘li’).find(‘.findme’);

    where as we can use the find() method on “

      ” to find it’s decedant “

    • ” elements having class “findme” as following:
      //Get all 'li' with class 'findme'
      $('ul').find('.findme')

      See live example here: http://jsfiddle.net/GAf7J/2/

      $(‘li’).filter(‘.findme’) Here $(‘li’) finds all the “li” elements and filter(“.findme”) searches element having class=’findme’ with in $(“li”) element set.

      $(‘li’).find(‘.findme’)

      Here find(‘.findme’) searches element having class=’findme’ in the child elements of all “li”. So no match found.

      $(‘ul’).find(‘.findme’)

      Here find(‘findme’) searches element having class=’findme’ in the decendants of “

        ”.

        Conclusion:

        If you want to select element(s) using find() or filter() then use find() in element’s parent or use filter() in current element selector set.

        References:

        .find()

  • 150 150 Burnignorance | Where Minds Meet And Sparks Fly!