JavaScript offsetParent Propety Tutorial

In this section, we will learn what the Element offsetParent property is and how to use it in JavaScript.

What is Element offsetParent Propety in JavaScript?

The JavaScript Element offsetParent property is used to get a reference to the closest element of the current element (the one that invoked the property) that:

  • First: this reference element is one of the ancestors of the current element.
  • Second: the CSS position property of the reference element is set to any value other than “static”.

JavaScript offsetParent Propety Syntax:

element.offsetParent;

JavaScript offsetParent Propety Input Value

The offsetParent property is read-only and so can’t assign a value to it.

JavaScript offsetParent Propety Return Value

The return value of this method, as mentioned before, is the closest element in the string of ancestors that has its position property set to a value other than “static”.

Note: the value of the offsetParent property might become null for the following reasons:

  • If the display property for the current element or its parent is set to none.
  • If the current element (the one that invoked the property) has the position property with the value fixed. (In a situation like this, the Firefox browser returns a reference to the <body> element).
  • If the current element is either <body> or <HTML> element.

Example: using offsetParent Property in JavaScript

See the Pen using offsetParent Propety in JavaScript by Omid Dehghan (@odchan1) on CodePen.

How does element offsetParent property work in JavaScript?

In this example, the position property of the <ol> element is set to fixed. Now, via the third item of this list and using the offsetParent property, we want to get a reference to the closest ancestor that is positioned at something other than “static” value. So here after calling this property, we got a reference to the <ol> element because this element’s position property is set to “fixed”.

That’s how we got a reference to the <ol> element.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies