jquery
  1. jquery-offsetparent

jQuery offsetParent()

The offsetParent() method in jQuery returns the first positioned parent element of a specified element. This can be useful for finding the offset position of an element relative to its parent element.

Syntax

The syntax for the offsetParent() method is as follows:

$(selector).offsetParent()

Where selector is the element we want to locate the offset parent for.

Use

The offsetParent() method is commonly used for calculating the offset position of a child element relative to its parent. It can be useful in situations where you need to position elements dynamically, such as in a draggable or resizable interface.

Example

Here is an example of using the offsetParent() method:

<div style="position: relative;">
  <div style="position: absolute; top: 10px; left: 10px;">
    <p>Hello World!</p>
    <p>Offset Parent is: <span id="parent"></span></p>
  </div>
</div>
const parent = $('p').offsetParent().get(0).nodeName;
$('#parent').text(parent);

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>jQuery Example</title>
  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
  
</head>
<body>


<div style="position: relative;">
  <div style="position: absolute; top: 10px; left: 10px;">
    <p>Hello World!</p>
    <p>Offset Parent is: <span id="parent"></span></p>
  </div>
</div>


  <script>
const parent = $('p').offsetParent().get(0).nodeName;
$('#parent').text(parent);


  </script>

</body>
</html>
Try Playground

In this example, we have a nested set of div elements with different position styles. We use the offsetParent() method to find the first parent element that has a position other than static. We then update the content of the span element to show the name of the offset parent element found by the selector.

Summary

The offsetParent() method in jQuery can be a useful tool for positioning elements dynamically on a page. It allows you to locate the first positioned parent element of a specified element, which can be used to calculate the offset position of the child relative to its parent. By understanding how to use this method, you can create more dynamic and interactive user interfaces.

Published on: