Use backgroundColor property in JavaScript to set a style background color of an HTML element.
document.body.style.backgroundColor = "green";
Change style background color example
HTML example code to change the background color of elements using JavaScript.
Change Webpage body-color
<html>
<body>
<p>Text sample Text</p>
</body>
<script>
document.body.style.backgroundColor = "green";
</script>
</html>
Output:
Change div tag color
If you’re using a DIV container with a different background color you will need to modify the background color of that instead of the document body.
Example how to set a background color of a specific element programmatically in JS:-
<html>
<body>
<p>Text sample Text</p>
<div id="myDiv"> Color Div</div>
</body>
<script>
document.getElementById("myDiv").style.backgroundColor = "lightblue";
</script>
</html>
Output:
Do comment if you have any doubts, questions, or suggestions on this topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version