Changing the Background Color of the Web Page Dynamically in JavaScript


The Style Property helps in changing the background color of the Web Page dynamically in the JavaScript. It returns the ‘CSS Style Declaration Object’ that highlights the style attributes of a particular element. Moreover, the Style Property is used to set or even get a specific style of an element using various CSS properties.

If you want to change the background color of a Web page or the <body> element or even any other element in the JavaScript then ‘Style Property’ dynamically carries out this change. The style property sets and gets the ‘inline style’ of the elements. Even any of the HTML elements, which support style attributes, also possess the style property. It can be cleared with the help of an example.


<!DOCTYPE html>

<html lang="en">


<meta charset="utf-8">

<title>Change the Background Color with JavaScript</title>


    // Function to change webpage background color

    function changeBodyBg(color){ = color;



    // Function to change heading background color

    function changeHeadingBg(color){

        document.getElementById("heading").style.background = color;





The above example clearly shows that the style property helps in changing the web page color with the applicability of this function. However, in any case, if you are using a DIV container or any other element then one needs to modify the background of that element instead of the web page document body.

Here one thing worth noting is that it is not possible to set the styles in JavaScript by assigning a string in the ‘Style Property’. The style property is said to return only the CSS declarations but this property does not give any vital information about the style rules or their applicability. Moreover, you cannot get information about the style rules used in the <head> section of any of the document or the external style sheets.

The example provided above shows that the usage of ‘style property’ instead of any kind of element attributes will help in not overwriting the CSS properties that may be otherwise specified in any of the style attributes used while designing the Web Page.

Even another important point relative to the style property is that if it is applied to any element then it only provides back its value. Like, if you want to change the background color of a specific web page or just the text body then ‘style property’ applicability will help in carrying out the needful.

View Demo

Leave a Reply

Your email address will not be published. Required fields are marked *