- jQuery Tutorial
- jQuery - Home
- jQuery - Overview
- jQuery - Basics
- jQuery - Syntax
- jQuery - Selectors
- jQuery - Events
- jQuery - Attributes
- jQuery - AJAX
- jQuery DOM Manipulation
- jQuery - DOM
- jQuery - Add Elements
- jQuery - Remove Elements
- jQuery - Replace Elements
- jQuery CSS Manipulation
- jQuery - CSS Classes
- jQuery - Dimensions
- jQuery - CSS Properties
- jQuery Traversing
- jQuery - Traversing
- jQuery - Traversing Ancestors
- jQuery - Traversing Descendants
- jQuery References
- jQuery - Selectors
- jQuery - Events
- jQuery - Effects
- jQuery - HTML/CSS
- jQuery - Traversing
- jQuery - Miscellaneous
- jQuery - Properties
- jQuery - Utilities
- jQuery Plugins
- jQuery - Plugins
- jQuery - PagePiling.js
- jQuery - Flickerplate.js
- jQuery - Multiscroll.js
- jQuery - Slidebar.js
- jQuery - Rowgrid.js
- jQuery - Alertify.js
- jQuery - Progressbar.js
- jQuery - Slideshow.js
- jQuery - Drawsvg.js
- jQuery - Tagsort.js
- jQuery - LogosDistort.js
- jQuery - Filer.js
- jQuery - Whatsnearby.js
- jQuery - Checkout.js
- jQuery - Blockrain.js
- jQuery - Producttour.js
- jQuery - Megadropdown.js
- jQuery - Weather.js
- jQuery Useful Resources
- jQuery - Questions and Answers
- jQuery - Quick Guide
- jQuery - Useful Resources
- jQuery - Discussion
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