Off the Ridge code

Off the Ridge Code Newsletter

Search

jQuery – Pro Tip #4 – jQuery Difference between find and filter

Published January 26, 2015 in jQuery - 1Comments

jQuery Difference between find and filter

If I have a list of items such as:

<ul id=”tasks”>
    <li class=”task”>Do some work</li>
    <li class=”task”>Do more work</li>
    <li class=”relax”>Relax!</li>
</ul>

and I’d like to select all list elements inside with class=”task” assigned.

I might want to do something like this:

// cache the result.
var $tasks = $(‘#tasks li’);

var $task = $tasks.find(‘.task’);

and that of course won’t work. The reason is this: http://api.jquery.com/find/

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

in other words it says: ‘search through all the child elements only’ and since we are already at the <li> level there’s nothing below it!

The solution to this is to use .filter() method that works on the currently matched elements.

var $task2 = $tasks.filter(‘.task’);

jsFiddle example: http://jsfiddle.net/seba368/gn8L204a/

  • http://BusinessFirstFamily.com/ great content

    Sometimes, the very best posts aren’t the most used, but that is great in my own book.