← Back to index

.find() | jQuery API Documentation

Created: 2015-12-10 06:44  |  Source: https://api.jquery.com/find/

jQuery API Documentation

Returns: jQuery

Description: Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

Given a jQuery object that represents a set of DOM elements, the .find() method allows us to search through the descendants of these elements in the DOM tree and construct a new jQuery object from the matching elements. The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree.

The first signature for the .find()method accepts a selector expression of the same type that we can pass to the $() function. The elements will be filtered by testing whether they match this selector.

Consider a page with a basic nested list on it:

< class="level-1">
< class="item-i">I</>
< class="item-ii">II
< class="level-2">
< class="item-a">A</>
< class="item-b">B
< class="level-3">
< class="item-1">1</>
< class="item-2">2</>
< class="item-3">3</>
</>
</>
< class="item-c">C</>
</>
</>
< class="item-iii">III</>
</>

If we begin at item II, we can find list items within it:

$( "li.item-ii" ).find( ).css( "background-color", "red" );

The result of this call is a red background on items A, B, 1, 2, 3, and C. Even though item II matches the selector expression, it is not included in the results; only descendants are considered candidates for the match.

Unlike most of the tree traversal methods, the selector expression is required in a call to .find(). If we need to retrieve all of the descendant elements, we can pass in the universal selector '*' to accomplish this.

Selector context is implemented with the .find() method; therefore, $( "li.item-ii" ).find( "li" ) is equivalent to $( "li", "li.item-ii" ).

As of jQuery 1.6, we can also filter the selection with a given jQuery collection or element. With the same nested list as above, if we start with:

allListElements = $( );

And then pass this jQuery object to find:

$( "li.item-ii" ).find( allListElements );

This will return a jQuery collection which contains only the list elements that are descendants of item II.

Similarly, an element may also be passed to find:

item1 = $( "li.item-1" )[ ];
$( "li.item-ii" ).find( item1 ).css( "background-color", "red" );

The result of this call would be a red background on item 1.