jQuery Traversal - offsetParent() Method
Example
Set the background color of the nearest positioned parent element of the li element with class name item-a:
$('li.item-a').offsetParent().css('background-color', 'red');
Definition and Usage
offsetParent() gets the nearest positioned ancestor element.
Syntax
.offsetParent()
Detailed Description
If a jQuery object representing a set of DOM elements is given, the .offsetParent() method allows us to search the DOM tree for the ancestors of an element and construct a jQuery object enclosed by the nearest positioned ancestor element. A positioned element refers to an element whose CSS position property is set to relative, absolute, or fixed. This information is very useful when calculating offsets for animations or placing objects on the page.
Please consider a page with a basic nested list that contains positioned elements:
<ul class="level-1"> <li class="item-i">I</li> <li class="item-ii" style="position: relative;">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 positioned ancestor elements:
$('li.item-a').offsetParent().css('background-color', 'red');
This will change the background color of the targeted item II.