×

jQuery Tutorial

jQuery Examples

jQuery Practice

jQuery offsetParent() Method

jQuery | offsetParent() Method: Learn about the jQuery offsetParent() Method with its usages, syntax, and examples.
Submitted by Pratishtha Saxena, on October 18, 2022

offsetParent() Method

The offsetParent() method of jQuery is a built-in method. It basically helps to return the first parent of the selected element which has been positioned using CSS or jQuery. The CSS position property can be – absolute, relative, or fixed. Hence, if the element has the position property then, the offsetParent() method will access it, otherwise, that parent element will be ignored and the method will move on to the next parent element of its if present.

offsetParent() Method Syntax

$("selector").offsetParent();

This method does not accept any parameter of its own. Only the selector of the element, whose parent element has to be selected, is passed. It then returns the first matched parent element of the selector. Therefore, we can provide some styling using css(), or apply some other jQuery methods for the selected parent element accordingly. Hence, once the required parent element has been found, we can manipulate it in any way needed.

The following example shows how the offsetParent() method changes the background color of the first positioned parent of the selected element.

jQuery offsetParent() Method Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  </head>
  
  <body>
    <h2>jQuery - offset Parent</h2>
    <span>Click the button to set the properties of the offset Parent of the selected element.</span><br><br>
    <button>Offset Parent</button>
    <hr>
    <br>
    <div style="border:1px solid black;width:70%;position:absolute;padding: 20px;">
      Outer Div
      <div style="border:1px solid black;margin:50px;background-color: blanchedalmond;">
        <p style="padding-left: 10px;">Welcome to Include Help !!!</p>
      </div>
    </div>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('button').click(function(){
            $("p").offsetParent().css('background-color','teal');
        });
    });    
  </script>
</html>

Output:

Example 1: jQuery offsetParent() Method


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.