In this tutorial we will see how to Add Class to Parent Tag on hover using jQuery. The jQuery hover() method, parent() method and addClass() method can be used to add class to the parent element of the child tag.
Table of Contents
jQuery hover() Method
jQuery hover() Method triggers the mouseenter and mouseleave events and it also defines two function to run when mouse hovers over an HTML tag and when mouse leaves that tag.
In this example hover() method runs two different functions to add and remove class from the parent element.
jQuery parent() Method
jQuery parent() Method returns the parent element of the child element.
In this example parent() method is used to target or select the parent element.
jQuery addClass() Method
jQuery addClass() Method adds one or more classes to the targeted element.
In this example addClass() method is used to add the class to the parent element.
HTML Code
HTML Code is given below, in this code we have a parent element, child element and a button tag. The ids of parent and child elements are also defined.
<!DOCTYPE html>
<html>
<head>
<title>jQuery on hover Add Class to Parent Tag</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<style>
#parent
{
padding: 50px 20px;
}
.red
{
background-color: red;
}
</style>
</head>
<body>
<div id="parent">
<button id="child">Hover Over Me</button>
</div>
<script src="script.js"></script>
</body>
</html>
JQuery Code
JQuery Code is given below, the code is executed whenever mouse hovers over button tag and when mouse hovers away from button tag.
jQuery parent() method will select the div tag which is parent element while the addClass() method will add the class to it.
removeClass() method is also used to remove the class when mouse hovers away from parent element.
Take a look at the code given below.
<script>
$(document).ready(function(){
$('#child').hover(function()
{
$(this).parent().addClass('red');
},
function()
{
$(this).parent().removeClass('red');
}
);
});
</script>
Demo
Video Tutorial
Watch video tutorial on How To Add Class to Parent Tag on hover with jQuery.