The methods I’m talking about are
filter(). They are all used to extend or refine a selection of html objects that you’ve already got. Typically you’ve already got a selection using the jQuery method, or $(expression), but need to refine it further.
All three of these methods have, that they take a jQuery expression as an argument, in common. A jQuery expression typically looks like a regular CSS selector like for example “#content”. You can use any kind of CSS selector, including the ones found in CSS 3. On top of that you can also use jQuery specific selectors. It’s a really powerful way of finding the right elements in a HTML document. To read more about how a expression could be constructed, check out the section about selectors in the jQuery documentation.
We will take a closer look on how these methods really works in the following section.
Examples and explanations
Consider the following HTML.
<div id="div1"> <p>Some text</p> </div> <div id="div2"> <p>Some more text</p> </div>
We’re going to use this HTML to do some selections from.
As the name implies this method is used to add more elements to a collection that you’ve already got. So if you have a <div> with the id “div1” in your selection and wants to add a <div> with the id “div2” to it,
add() is the method to use:
// This code will add div2 to the collection that already contains div1 $('#div1').add('#div2');
Find() on the other hand is used to find descendant element from your selection. So instead of adding more elements to it it narrows it down to fewer elements. It searches what’s inside the parent element(s) in your selection. In the example below it will search for content inside of the selected <div> that matches the expression.
// Refine the selection to contain only the &lng;p< elements inside of #div1 $('#div1').find('p');
Filter() is quite similar to
find() but instead of searching the descendant elements of the selection it “searches”, or rather filters, the elements that are in the selection.
// Reduces the selection to only contain the <div> with the id "div1" $('div').filter('#div1');
I’ve constructed a simple demo page which demonstrates how these methods work. Please try it out.
All of these methods are very useful but it’s important to know which one to choose in a given situation. If you want to extend your selection to include more elements you should use
add(). If you want to narrow down your selection you need too use either
Of course there are many other useful methods to traverse the DOM in jQuery. Which ones are your favorites?