jQuery offsetParent() Method



The offsetParent() method in jQuery is used to get the closest positioned ancestor element of the selected element.

You can position an element either using jQuery or by utilizing the CSS position property such as relative, absolute, or fixed positioning.

Syntax

Following is the syntax of offsetParent() method in jQuery −

$(selector).offsetParent()

Parameters

This method does not accept any parameters.

Example

In the following example, we are using the offsetParent() method to find the closest positioned parent element of the <p> element −

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        // Find the offset parent of the p element
        const offsetParent = $("p").offsetParent();
            // Check if the offset parent exists
        if(offsetParent !== null) {
            // Set the background color of the offset parent to green
            offsetParent.css("background-color", "green");
            alert("offset parent found. It will now be highlighted with green color.");
        } else {
            alert("No offset parent found.");
        }
    });
});
</script>
</head>
<body>
<div style="border:1px solid black; width: 30%; position:absolute; left:10px; top:50px" >
   <div style="border:1px solid black; margin:50px; background-color:yellow">
      <p>Click on the above button to find and set background color for the first positioned parent element of this paragraph.</p>
   </div>
</div>
<button>Click here!</button>
</body>
</html>

After executing the above program, if we click on the button, it method finds out the offset parent of the <p> element, gives an alert, and sets its background color to green.

jquery_ref_traversing.htm
Advertisements