jQuery Traversal - parents() Method
Definition and Usage
The parents() method gets the ancestor elements of each element in the current matched element set, using a selector for filtering is optional.
.parents()selector)
Parameter | Description |
---|---|
selector | String value, containing the selector expression used to match elements. |
Detailed Description
If a jQuery object representing a set of DOM elements is given, the .parents() method allows us to search for ancestor elements of these elements in the DOM tree and construct a new jQuery object with matching elements ordered from the nearest parent upwards. Elements are returned in order from the nearest parent outward. .parents() and .parent() The method is similar, but the latter traverses a single level up the DOM tree.
This method accepts an optional selector expression, of the same type as the parameters passed to the $() function. If this selector is applied, the elements will be filtered by checking whether they match the selector.
Consider this page with a basic 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>
If we start from item A, we can find its ancestor elements:
$('li.item-a').parents().css('background-color', 'red');
The result of this call is that the elements such as level-2 list, item II, and level-1 list, etc. (all the way up to <html>) have their background color set to red. Since we did not apply a selector expression, the parent element naturally became part of the object. If a selector had been applied, the element would have been checked for a match before it was included. Since we did not apply a selector expression, all ancestor elements are part of the returned jQuery object. If a selector had been applied, only the matching items would have been included.