Home >>jQuery Tutorial >jQuery parents() Method

jQuery parents() Method

jQuery parents() Method

jQuery parents() method in jQuery is used to returns all ancestor (An ancestor is a parent, grandparent, great-grandparent, and so on) elements of the selected element.

Syntax:
$(selector).parents(filter)

Parameter Values

Parameter Description
filter It is an Optional parameter and is used to specifies a selector expression to narrow down the search for ancestors
Here is an Example of jQuery parents() Method:

<html>
<head>
<style>
.ancestors * { 
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("span").parents().css({"color": "#22a5bf", "border": "2px solid #22a5bf"});
});
</script>
</head>
<body>
<div class="ancestors">
<div style="width:500px;">div (great-grandparent)
<ul>ul (grandparent)  
<li>li (direct parent)
<span>span</span>
</li>
</ul>   
</div>
</div>
</body>
</html>

Output:
div (great-grandparent)
    ul (grandparent)
  • li (direct parent) span

No Sidebar ads