jQuery offsetParent()

Introduction

Set the background color of the closest positioned parent element of the <p> element:

Click button to set the background color of the first positioned parent element of this paragraph.

View in separate window

<!DOCTYPE html>
<html>
<head>
<script 
 src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>//from   w  w w. j a  va  2s.c o  m
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").offsetParent().css("background-color", "red");
  });
});
</script>
</head>
<body>

<button>Set background-color</button>

<div style="border:1px solid black;width:70%;position:absolute;left:10px;top:50px">
<div style="border:1px solid black;margin:50px;background-color:yellow">

</div></div>

</body>
</html>

The offsetParent() method returns the first positioned parent element.

$(selector).offsetParent()



PreviousNext

Related