Search

API: Filter & Find

Posted on 6th January 2009 — As the first in the series of API screencasts, but also as a good beginners tutorial, this short episode shows the difference between filter and find.

Please note that I’ll continue to include full tutorial write ups with the J4D screencasts – whereas playschool and API will have a limited post accompanying them.

Watch

Watch the jQuery filter & find screencast (alternative flash version)

QuickTime version is approximately 20Mb, flash version is streaming.

View the demo and source code used in the screencast

Filter vs. Find

jQuery’s chaining makes working with the library incredibly expressive.

Such as:

$('div').animate({'opacity' : 0.5}, 500).addClass('warning');

Reads (fairly) easily to “animate the div’s opacity to 0.5 and add a class of ‘warning’”.

However, I still find that there’s sometimes confusion over using filter and find.

jQuery’s Definition

Filter

Removes all elements from the set of matched elements that do not match the specified function.

Find

Searches for all elements that match the specified expression. This method is a good way to find additional descendant elements with which to process.

The Difference

I’ve found the easiest way to understand the difference, is to think of find working down the DOM.

filter changes the current collection of elements, and does not search the DOM for new nodes to add to our collection.