Geek and software developer who started writing in Basic (on Atari, Commodore and Amiga 500) in the 80's. I teach via this blog and videocasts. I have a lot of computers and even more monitors. Contact me at sebastian at brukalo dot com
Off the Ridge code
If I have a list of items such as:
<li class=”task”>Do some work</li>
<li class=”task”>Do more work</li>
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/