HTMLElement: offsetParent property

发布时间 2023-11-27 18:02:54作者: ChuckLu

HTMLElement: offsetParent property

The HTMLElement.offsetParent read-only property returns a reference to the element which is the closest (nearest in the containment hierarchy) positioned ancestor element.

A positioned ancestor is either:

  • an element with a non-static position, or
  • td, th, table in case the element itself is static positioned.

If there is no positioned ancestor element, the body is returned.

Note: offsetParent returns null in the following situations:

  • The element or any ancestor has the display property set to none.
  • The element has the position property set to fixed (Firefox returns <body>).
  • The element is <body> or <html>.

offsetParent is useful because offsetTop and offsetLeft are relative to its padding edge. 

 

How can I find which element was used as the current element's top 50% position absolute

 

To find the parent element that a positioned child element is using as its reference, you can use JavaScript:

js

 

Copy code

let positionedElement = document.querySelector(".positioned"); let offsetParent = positionedElement.offsetParent;

The offsetParent property will return the closest positioned ancestor that the absolutely positioned element is using to offset itself.

A positioned element is one that has a position value other than the default static. This would include relative, absolute, fixed, and sticky.

So in this example:

html

 

Copy code

<div class="parent" style="position: relative"> <div class="positioned" style="position: absolute; top: 50%">...</div> </div>

The .positioned div is positioned absolutely at 50% from the top.

Its offsetParent will be the .parent div, since that has position: relative applied.

So using offsetParent allows you to dynamically find that positioned ancestor.

 

 

loop to find all positioned ancestors of element with id "userListTable_processing"

// Get reference to element
const elem = document.getElementById("userListTable_processing");

// Stores positioned ancestors  
const positionedAncestors = [];

// Loop upwards through parents 
let parent = elem.parentNode;
while (parent) {

  // Check if positioned
  if (parent.style.position === "relative" || 
      parent.style.position === "absolute" ||
      parent.style.position === "fixed") {
        
    // Add to array        
    positionedAncestors.push(parent);
  }

  // Go up to next parent 
  parent = parent.parentNode; 
}

// Print positioned ancestors
positionedAncestors.forEach(el => {
  console.log(el); 
});