jQuery parent() Method - CodingTag
×


jQuery parent()

1187

  • This jQuery method is used to fetch the direct parent or ancestor element of the selected HTML element.
  • If we talk about the DOM traversal tree, this method can only traverse the DOM tree at single level upward.
  • To traverse the all grandparents or ancestors of the selected element, use either the parents() or parentsUntill() jQuery methods.
  • If you want to traverse the direct child or descendent elements of selected HTML element use either find() or chidren() jQuery methods.

Related Topics:

jQuery wrapAll
jQuery unwrap

jQuery parent

Syntax:

$(selector).parent(filter) ;

Parameter description:

  • filter: This parameter is used to represents a selector expression to narrow down the parent search. It is optional.

Example 1

In this example we will return the direct parents of all <b> elements and highlight them.

<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 red");
});
});
</script>
</head>
<body>

<h2> jQuery parent() method Example </h2>
<div>
<p><b> Hello Friends!! </b> </p>
<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 parent of the list item which has the class demo and highlight them.

<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(){
$("li").parent("ul.demo").css("border","2px solid red");
});
});
</script>
</head>
<body>

<h2> jQuery parent() method Example </h2>
<div>
<p> List 1 </p>
<ul>
<li> Maths </li>
<li> Science </li>
</ul>
<p> List 2 </p>
<ul class="demo">
<li> Ram </li>
<li> Shyam </li>
</ul>
<p> List 3 </p>
<ul>
<li> Seeta </li>
<li> Geeta </li>
</ul>
</div>
<button> Click Me! </button>
</body>
</html>

Output:

When you click the button,



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments