How to add class to parent div using jQuery

By | May 24, 2021

In this blog, I am going to share with you a small how to guide that will be helpful for you if, you are looking for the code to add a class to parent div using jQuery library.

Let’s say, you have structured your HTML document as following and you are interested in adding a class ‘my-parent’ to parent class.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Add class to parent div using jQuery</title>
  <style>
	#parent_div{width: 300px;border: 15px solid green;padding: 50px;margin: 20px; text-align:center;}
	.my-parent{background-color:red;}
  </style>
</head>
<body>
	<div id="parent_div">
		<input type="button" id="click_button" value="Click Me" />
	</div>
</body>
</html>

Now, we will write jQuery code to add a class to parent div.

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script type="text/javascript">
	$(function() {
	    $('#click_button').click(function(e){
		  $(this).parent().addClass('my-parent');
		});
	});
  </script>

Here is complete code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Add class to parent div using jQuery</title>
  <style>
	#parent_div{width: 300px;border: 15px solid green;padding: 50px;margin: 20px; text-align:center;}
	.my-parent{background-color:red;}
  </style>
</head>
<body>
	<div id="parent_div">
		<input type="button" id="click_button" value="Click Me" />
	</div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script type="text/javascript">
	$(function() {
	    $('#click_button').click(function(e){
		  $(this).parent().addClass('my-parent');
		});
	});
  </script>
</body>
</html>

The Output: