jQuery Traversal - parent() Method
Example
Find the parent elements of each paragraph with the 'selected' class:
$("p").parent(".selected")
Definition and Usage
The parent() method gets the parent element of each element in the current matching element set, and using a selector to filter is optional.
.parent(selector)
Parameter | Description |
---|---|
selector | String value, containing a selector expression used to match elements. |
Detailed Explanation
If a jQuery object representing a collection of DOM elements is given, the .parent() method allows us to search for the parent elements of these elements in the DOM tree and construct a new jQuery object with matching elements..parents() Similar to the .parent() method, the difference is that the latter traverses a single level up the DOM tree.
This method accepts an optional selector expression, which is the same type of parameter as the one we pass to the $() function. If this selector is applied, it will filter elements by checking whether they match the selector.
Think about 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 parent element:
$('li.item-a').parent().css('background-color', 'red');
The result of this call is to set the red background for the level-2 list. Since we did not apply a selector expression, the parent element naturally became part of the object. If a selector is applied, it will check whether the element matches the selector before including the element.