Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an element IS an offsetParent

Is there a convenient way to check if an HTMLElement is an offsetParent?

I have a situation where I need to determine an element's offsetParent before it is inserted in the DOM. I can access the element's immediate parent, before insertion.

There doesn't seem to be any properties on HTMLElements that indicate whether or not it is an offsetParent.

Is there a good way to do this?

like image 330
oorst Avatar asked Jun 18 '19 05:06

oorst


1 Answers

There is to my knowledge unfortunately nothing in the DOM API that does expose this information on the Element itself.

According to specs, an ancestor can be an offsetParent if

The element is a containing block of absolutely-positioned descendants

This means that not only positioned elements will qualify, but any element with a transform, or a filter property, a will-change with a value containing any of the aforementioned ones will also do.

However this behavior was not always specified this way, so it may return false positives in some browsers.
Also, it may be that in the future other CSS properties will affect what makes a containing block, or even in the present since I only got these from the tip of my head...

With that in mind, the surest is to append a test element inside your element and to check its offsetParent.
However, this will create forced reflows, so use it sporadically.

document.querySelectorAll('.container > div')
  .forEach(elem => {
    elem.textContent = isOffsetParent(elem) ? 'offsetParent' : 'not offsetParent';
  });

function isOffsetParent(elem) {
  const test = document.createElement('span');
  elem.appendChild(test);
  const result = test.offsetParent === elem;
  elem.removeChild(test);
  return result;
}
<div class="container">

  <div class="is-offset-parent" style="position:relative"></div>
  <div class="can-be-offset-parent" style="transform:translate(0)"></div>
  <div class="can-be-offset-parent" style="filter:blur(1px)"></div>
  <div class="is-not"></div>

</div>

But if you really wish some unsafe way which may need to be updated, then you could check all the properties I mentioned before using getComputedStyle(elem).

like image 188
Kaiido Avatar answered Oct 13 '22 18:10

Kaiido