JavaScript style background color | HTML Example code

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 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:

Change div tag color JavaScript program

Do comment if you have any doubts, questions or suggestion 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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.