Changing the background color of a div using jQuery is done simply by using the css() method.

$("#div").css("background-color", "green");

Let’s say we have the following HTML:

This paragraph is in a div that we need to change the color of.

If we want to change the background color of this div to green, we will use the jQuery css() method in the following JavaScript code.

$("#div").css("background-color", "green");

If you are using WordPress, don’t forget to change the $ to jQuery as below:

jQuery("#div").css("background-color", "green");

The second argument can be any valid css color. So for example, we could use the hexadecimal value for green to change the background color to green.

$("#div").css("background-color", "#00FF00");

Using jQuery to Change Background Color of a Div with a Click

Many times when creating a web page and the user experience, we want to change the color of a div and interact with another element on the web page.

To change the background color of a div using jQuery, we can combine the css() method with a click event.

Let’s say we have the following HTML and we want to change the background color of #div1 to green.

Div 1
Div 2
Change background color of #div1

We can utilize both the jQuery click() method and jQuery css() method to change background color.

Below is the JavaScript code which will allow the user to be able to update the background color of the div:

$("#click-me").click(function(){
  $("#div1").css("background-color", "#7bbfa2");
}); 

The final code and output for this example of how to change the background color of our div using the jQuery css() method and JavaScript is below:

Code Output:

Div 1
Div 2
Change background color of #div1

Full Code:

Div 1
Div 2
Change background color of #div1
<script> $("#click-me").click(function(){ $("#div1").css("background-color", "#7bbfa2"); }); </script>

Hopefully this article has been useful for you to understand how to change the background color of an element using jQuery.

Categorized in:

jQuery,

Last Update: February 26, 2024