jQuery Traversal - find() Method
Example
Search for all descendant span elements within all paragraphs and set their color to red:
$("p").find("span").css('color','red');
Definition and usage
The find() method retrieves the descendants of each element in the current element collection, filtering them by selector, jQuery object, or element.
Syntax
.find(selector)
Parameter | Description |
---|---|
selector | String value, containing the selector expression to match the current element collection. |
Detailed explanation
If a jQuery object representing a set of DOM elements is given, the .find() method allows us to search for these elements' descendants in the DOM tree and construct a new jQuery object with the matching elements. .find() is similar to .children() method, the difference being that the latter only traverses a single level down the DOM tree.
.find() method's first obvious feature is that it accepts a selector expression of the same type as the one we pass to the $() function. It filters elements by testing whether they match the expression.
Please think about the following simple nested list:
<ul class="level-1"> <li class="item-i">I</li> <li class="item-ii">II <ul class="level-2"> <li class="item-a">A</li> <li class="item-b">B <ul class="level-3"> <li class="item-1">1</li> <li class="item-2">2</li> <li class="item-3">3</li> </ul> </li> <li class="item-c">C</li> </ul> </li> <li class="item-iii">III</li> </ul>
We will start from the list II to find the list items within it:
$('li.item-ii').find('li').css('background-color', 'red');
The result of this survey is that projects A, B, 1, 2, 3, and C have all been set to a red background. Even if project II matches the selector expression, it will not be included in the result; only descendants will be matched.
Unlike other tree traversal methods, a selector expression is a required parameter for .find(). If we need to retrieve all descendant elements, we can pass the wildcard selector '*'.
The selector context is implemented by the .find() method; therefore, $('li.item-ii').find('li') is equivalent to $('li', 'li.item-ii').
For jQuery 1.6, we can also use the given jQuery collection or element for filtering. Continuing with the nested list, we first write:
var $allListElements = $('li');
Then pass this jQuery object to the find method:
$('li.item-ii').find($allListElements);
The above code will return a jQuery collection containing list elements that are descendants of the list II.
Similarly, you can also pass an element:
var item1 = $('li.item-1')[0]; $('li.item-ii').find(item1).css('background-color', 'red');
The result of this call is that project 1 has been set to a red background.