Monday, January 26, 2015

jQuery - Pro Tip #4

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/

No comments:

Post a Comment