How to DIV Change Background Color in JavaScript

In this tutorial, you will learn how to change div background color in javascript. The div element is a block-level element and we generally use it as a container for other elements.

You can specify a default background color for any element using CSS, but to change it dynamically, we have to make use of javascript.

Each element has certain DOM properties and style property is one of them. This property can be used to change the styles of any element.

To get or set the background color of any element, we can make use of the backgroundColor property. If you have not set the background color for an element using CSS, then this property will return transparent as a default value.

In the following example, we have a button element and a div element with a background color of red. Upon click of a button, we will change the background color of the div element from red to green.  Please have a look over the code example and the steps given below.

HTML & CSS

  • We have 2 elements in the HTML file (div and button). The div element with a class of container is just a wrapper for the rest of the elements.
  • The innerText for the button element is "Click Here”.
  • By default, the div element with an id of myDiv has a background color of red. We will change it to green using javascript.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>
</head>

<body>

  <div class="container">
   <button>Click Here</button>
   <div id="myDiv"></div>
  </div>

  <script src="script.js"></script>
</body>

</html>
.container {
    width: 400px;
    margin: auto;
    display: flex;
    flex-direction: column;
}

button  {
  padding: 5px 10px;
}

#myDiv {
  height: 400px;
  width: 400px;
  background-color: red;
  margin-top: 10px;
}

Javascript

  • We have selected the div element and the button element using the document.querySelector() method and stored them in myDiv and btn variables respectively.
  • We have attached the click event listener to the button element.
  • In the event handler function, we are changing the background color of the div element from red to green by using the backgroundColor property.
let myDiv = document.querySelector("#myDiv");
let btn = document.querySelector("button");

btn.addEventListener("click", () => {
  myDiv.style.backgroundColor = "green";
});