In HTML, the offsetParent property is used to return the nearest ancestor of an element. The ancestor returned must have a position other than static. The offestParent property returns a null value if the element is set to display="none".
Syntax
object.offsetParent;This property is used to return the offsetParent of an element. This method has no default value. The offsetParent is a useful property because offsetTop and offsetLeft are relative to its padding edge.
Example 1: This example returns the offsetParent property.
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
<title>
HTML DOM Element offsetParent Property
</title>
</head>
<body>
<div id = "GFG">
<h1>GeeksforGeeks</h1>
<p>The offsetParent:
<span id="geeks"></span>
</p>
<!--Driver Code Ends-->
<button onclick="myGeeks()">
Click Here!
</button>
</div>
<script>
function myGeeks() {
var offsetp =
document.getElementById("GFG");
document.getElementById("geeks").innerHTML =
offsetp.offsetParent;
}
</script>
<!--Driver Code Starts-->
</body>
</html>
<!--Driver Code Ends-->
Example 2: This example use display property to hide the offsetParent value.
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
<title>
HTML DOM Element offsetParent Property
</title>
<style>
#GFG {
display: none;
}
</style>
</head>
<body>
<div id = "g4g">
<h1 id = "GFG">GeeksforGeeks</h1>
<button onclick="myGeeks()">
Click Here!
</button>
<p>The offsetParent:
<span id="geeks"></span>
</p>
</div>
<!--Driver Code Ends-->
<script>
function myGeeks() {
var offsetp = document.getElementById("GFG");
document.getElementById("geeks").innerHTML = offsetp.offsetParent;
}
</script>
<!--Driver Code Starts-->
</body>
</html>
<!--Driver Code Ends-->
- It returns the nearest positioned ancestor (an element whose position is not static, or certain special cases like a containing block, an element with a different effective zoom, or <td>/<th>/<table> for statically positioned elements). If none exists, it returns the <body> element. This is the reference point used by offsetLeft and offsetTop.
- This makes it useful for detecting when offset calculations are unavailable or when an element is hidden/fixed.