• jQuery Video Tutorials

jQuery offsetParent() Method



The offsetParent() method in jQuery identifies and returns the first positioned ancestor element. In other words, It retrieves the first parent element of the selected element that has a position.

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 return the "id" of the first positioned parent element for the <div> element with class "child" −

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $("#btn").click(function(){
    var parent = $("#child").offsetParent().attr('id');
    alert("Offset parent ID: " + parent);
  });
});
</script>
</head>
<body>
<div id="parent" style="position:relative; border:1px solid black; padding:20px;">
  <div id="child" style="position:relative; border:1px solid red;">
    Child Element
  </div>
</div>
<button id="btn">Get Offset Parent</button>
</body>
</html>

When we click the button, it returns the "id" of the first positioned parent element (div) "parent".

jquery_ref_html.htm
Advertisements