HTMLElement: offsetParent property

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"

function findPositionedAncestors(element) {
  const positionedAncestors = [];
  let currentElement = element;

  while (currentElement !== null) {
    const computedStyle = window.getComputedStyle(currentElement);
    if (computedStyle.position !== 'static') {
      positionedAncestors.push(currentElement);
    }

    currentElement = currentElement.parentElement;
  }

  return positionedAncestors;
}

const userListTableProcessingElement = document.getElementById('userListTable_processing');
const positionedAncestors = findPositionedAncestors(userListTableProcessingElement);
console.log(positionedAncestors);

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章