How can I change the background color of a div using jQuery code?

By | June 3, 2021

Hey there, Hope you are doing well.

Today, we are going to learn to change the background color of a div using jQuery code. This is going to be one line of the code and that can change the background color of a div in jQuery.

Lets say, you have div and ‘myDiv’ is assigned as id.

<div id="myDiv" class="abc container inner_div">
	<h4>Welcome to Lipku.com</h4>
	<p>Lorem Ipsum is simply dummy text of the printing and typesetting     industry. </p>
</div>

Now, You want to change the background color of ‘myDiv’. To do that, we can use .css method of jQuery.

$(function() {
   $('#myDiv').css('background-color', 'green');
});

Here is the complete code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>change the background color of a div using jQuery</title>
  <style>
	#myDiv{width: 300px;border: 15px solid green;padding: 50px;margin: 20px; text-align:center;}
  </style>
</head>
<body>
	<div id="myDiv" class="abc container inner_div">
	<h4>Welcome to Lipku.com</h4>
	<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. </p>
	</div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script type="text/javascript">
	$(function() {
	   $('#myDiv').css('background-color', 'green');
	});
	
  </script>
</body>
</html>

Before and After results: