jQuery parents()
0 1284
- This jQuery method is used to fetch the parents, all grandparents or all ancestor elements of the selected HTML element.
- If we talk about the DOM traversal tree, this method traverses the DOM tree upward from direct parent to all ancestor elements.
- To traverse only the direct parent element of the selected element, use parent() jQuery method.
- If you want to traverse the direct child or descendent elements of selected HTML element use either find() or children() jQuery methods.
Related Topics:
jQuery innerHeight
jQuery outerHeight
jQuery parents
Syntax:
$(selector).parents(filter) ;
Parameter description:
- filter: This parameter is used to represents a selector expression to narrow down the parent search. It is optional.
To return multiple ancestors, separate each expression with a comma.
Example 1
In this example we will return all the ancestors of all <b> elements.
<html>
<head>
<title> jQuery Example </title>
<script type = "text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<style>
div{
background:pink;
padding:10px;
margin:10px;
font-size:20px;
}
p{
background:yellow;
padding:10px;
margin:10px;
}
button{
background:green;
padding:10px;
color:white;
border:1px solid green;
}
</style>
<script>
$(document).ready(function(){
$("button").click(function(){
$("b").parent().css("border","2px solid green");
});
});
</script>
</head>
<body>
<h2> jQuery parents() method Example </h2>
<div>
<p><b> Hello Friends!! </b></p>
</div>
<div>
<p><b> Welcome to CodingTag </b></p>
</div>
<button> Click Me! </button>
</body>
</html>
Output:
When you click the button,
Example 2
In this example, we return the ancestors of <b> element that are child of div with demo class.
<html>
<head>
<title> jQuery Example </title>
<script type = "text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<style>
div{
background:pink;
padding:10px;
margin:10px;
font-size:20px;
}
p{
background:yellow;
padding:10px;
margin:10px;
}
button{
background:green;
padding:10px;
color:white;
border:1px solid green;
}
</style>
<script>
$(document).ready(function(){
$("button").click(function(){
$("b").parents('div.demo').css("border","2px solid red");
});
});
</script>
</head>
<body>
<h2> jQuery parents() method Example </h2>
<div class="demo">
<p><b> Hello Friends!! </b> </p>
</div>
<div>
<p><b> Welcome to CodingTag </b> </p>
</div>
<button> Click Me! </button>
</body>
</html>
Output:
When you click the button,
Share:
Comments
Waiting for your comments