find and filter in jQuery when and how to use

find and filter in jQuery when and how to use

Thanks to JQuery, handling javascript has never been easy. Bigger things while working on the client side would be querying the DOM for specific components. Among the tremendously many options, I would discuss the find and filter.
For illustration of the discussion let’s have the following example HTML:

<div class="upper"><p>Upper text goes here</p><div>
<div class="upper"><p>Another <b>Upper text goes</b> here</p><div>
<div class="middle"><p>middle <b>text goes</b> here</p><div>
<div class="lower">lower <b>text goes</b> here<div>
<div class="lower"><p>still another lower <i>text goes</i> here</p><div>

Using Filter

Filter would provide all the given components which are screened by the given condition. the query:
jQuery(‘div’).filter(‘.upper’) would provide two elements of div that have class upper on them. so alert(jQuery(‘div’).filter(‘.upper’).length) would alert two. Changing the class to middle and lower would result one and two respectively.

Using Find

Find, like the filter would provide elements and unlike filter, it would apply filtering on the children of the given component. Here is an example


This query would select the ‘p’ tag under every div element and would apply the class ‘border-it’ to the ‘p’ element only. Which means, it would iterate on the given condition on the parent component.

Finding all the bolds and underlining them would be:

jQuery('div').find('p').find('b').css('text-decoration', 'underline');

Also, this can be done ins succinct way as:

jQuery('div p b').css('text-decoration','underline');

How about if we want to select both the parent and the selected child:

In this case the handy method andSelf() would be there. Say if we want to border only the bold text and that of the enclosing div, we would have:

jQuery('div').find('p').find('b').andSelf().css('border', '1px black solid');
jQuery bind/unbind not working on firefox or in some other browsers

Date Picker in jQuery misses next and prev arrow. How to add arrow on jQuery date picker

Dynamically populate select box from JSON in javascript/jQuery

jQuery – Simple & Powerful

Leave a Reply

Your email address will not be published. Required fields are marked *