Tutorials using JS
Problem Statement
In this tutorial, you shall learn how to change background color of a div element using JavaScript.
Solution
To set or change the background color of a div element using JavaScript, we can use Element.style.background
property. Get the div element and set its style.background
property with the required color value.
divElement.style.background = 'green';
Program
When user clicks on the Click me
button, we get the div element with the id myDiv
and set its background color to 'green'
using style.background
property.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<button id="myBtn">Click me</button>
<div id="myDiv">About</div>
<style>
#myDiv {
width: 100px;
height: 100px;
background: yellow;
}
</style>
<script>
document.getElementById("myBtn").addEventListener("click", function() {
//get the div element
const myDiv = document.getElementById("myDiv");
//set the background color of the div
myDiv.style.background = 'green';
});
</script>
</body>
</html>