offsetParent property
The offsetParent property contains
the closest parent relative to which an
element is positioned. This will either
be the closest parent whose CSS
position
property is not equal to static,
or the body
tag if there is no parent with this
positioning.
Syntax
element.offsetParent;
Example
Let's find the parent element with
position other than
static:
<div id="parent3">
<div id="parent2" style="position: relative">
<div id="parent1">
<p id="elem">text</p>
</div>
</div>
</div>
let elem = document.querySelector('#elem');
console.log(elem.offsetParent.id);
The code execution result:
'parent2'
Example
If parent elements have no positioning,
then offsetParent contains
body:
<div>
<p id="elem">text</p>
</div>
let elem = document.querySelector('#elem');
console.log(elem.offsetParent.tagName);
The code execution result:
'BODY'
See also
-
the
offsetParentproperty
that contains a parent with positioning -
the
offsetTopproperty
that contains the top offset of an element -
the
offsetLeftproperty
that contains the left offset of an element -
the
getBoundingClientRectmethod
that finds the offset of an element