tadam logo
Did you find an error in the text?
Select this with mouse and press
Ctrl + Enter
Xhtml.co.il Check Spelling
Orphus system

offsetParent()

.offsetParent()

Returns: jQuery

Description: Get the closest ancestor element that is positioned.

.offsetParent()

version added: 1.2.6

Given a jQuery object that represents a set of DOM elements, the .offsetParent() method allows us to search through the ancestors of these elements in the DOM tree and construct a new jQuery object wrapped around the closest positioned ancestor. An element is said to be positioned if it has a CSS position attribute of relative, absolute, or fixed. This information is useful for calculating offsets for performing animations and placing objects on the page.

Consider a page with a basic nested list on it, with a positioned element:

<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 begin at item A, we can find its positioned ancestor:

$('li.item-a').offsetParent().css('background-color', 'red');

This will change the color of list item II, which is positioned.

Examples

Find the offsetParent of item "A."
$('li.item-a').offsetParent().css('background-color', 'red');
The output of the code above will be:
Full source:
<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript" language="javascript">
     $(document).ready(function(){
     $('li.item-a').offsetParent().css('background-color', 'red');
     });
  </script>
</head>
<body>
    <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>
</body>
</html>
Was this information helpful?
   

Comments