Given an HTML document and the task is to get the parent class of an element with the help of given class name.
Approach 1:
html
Output:
html
Output:
- The on() method is used to select the event handler for selected elements. It means when the user clicks the button then the function call.
- The closest() method is used to return the first ancestor of the selected elements.
- Check if ancestor (parent) class exist then it returns the class name otherwise returns not exist.
<!DOCTYPE html>
<html>
<head>
<title>
How to find a parent class
name with a known class
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p id="GFG_UP" style=
"font-size: 17px; font-weight: bold;">
</p>
<div class="parent">
<div class="child"></div>
</div>
<button>
click here
</button>
<p id="GFG_DOWN" style=
"color: green; font-size: 24px; font-weight: bold;">
</p>
<script>
$('#GFG_UP').text('Click on the button to see result');
$('button').on('click', function() {
var object = $('.child').closest('.parent');
if (object.length) {
$('#GFG_DOWN').text("className = '.child'"
+ " with parentName = '.parent'" + " Exists");
}
else {
$('#GFG_DOWN').text("Not Exists");
}
});
</script>
</body>
</html>
-
Before clicking the button:
-
After clicking the button:
- The on() method is used to select the event handler for selected elements. It means when the user clicks the button then the function call.
- The parent() method is used to return all ancestor of the selected elements.
- Check if ancestor (parent) class exist then it returns the class name otherwise returns not exist.
<!DOCTYPE html>
<html>
<head>
<title>
How to find a parent class
name with a known class
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p id="GFG_UP" style=
"font-size: 17px; font-weight: bold;">
</p>
<div class="parent">
<div class="child"></div>
</div>
<button>
click here
</button>
<p id="GFG_DOWN" style=
"color: green; font-size: 24px; font-weight: bold;">
</p>
<script>
$('#GFG_UP').text('Click on the button to see result');
$('button').on('click', function() {
var object = $('.child').parents('.parent');
if (object.length) {
$('#GFG_DOWN').text("className = '.child'"
+ " with parentName = '.parent'" + " Exists");
}
else {
$('#GFG_DOWN').text("Not Exists");
}
});
</script>
</body>
</html>
-
Before clicking the button:
-
After clicking the button:
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it's philosophy of “Write less, do more". You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.