Changing the background color of a div using JavaScript is done simply by using the backgroundColor property.
document.getElementById("div1").style.backgroundColor = "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 #div1 to green, we will use the backgroundColor property in the following JavaScript code.
document.getElementById("div1").style.backgroundColor = "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.
document.getElementById("div1").style.backgroundColor = "#00FF00";
Using JavaScript to Change the Background Color of a Div with a Click
To change the background color of a div using JavaScript, we can target the backgroundColor property with a click event.
Let’s say we have the following HTML and we want to change the background color of #div1 to green.
We can utilize both the backgroundColor property of #div1 along with an onclick event to change the background color.
Below is the JavaScript code which will allow the user to be able to update the background color of the div:
function clickFunction() {
var currDiv = document.getElementById("div1");
currDiv.style.backgroundColor = "green";
}
The final code and output for this example of how to change the background color of our div using JavaScript is below:
Code Output:
Full Code:
<script>
function clickFunction() {
var currDiv = document.getElementById("div1");
currDiv.style.backgroundColor = "green";
}
</script>
Hopefully this article has been useful for you to understand how to change the background color of an element using JavaScript.