How to change the background color of a web page dynamically using JavaScript

  4736 views   2 years ago Javascript

Use the JavaScript style property

You can easily change the background color of a webpage i.e. the <body> element or any other element dynamically by using its style property in JavaScript.

The style property is used to get as well as set the inline style of an element. Typically, any HTML element that supports the style attribute also has a style property. Here's 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;
    <h1 id="heading">This is a heading</h1>
    <p>This is a paragraph of text.</p>
        <label>Change Webpage Background To:</label>
        <button type="button" onclick="changeBodyBg('yellow');">Yellow</button>
        <button type="button" onclick="changeBodyBg('lime');">Lime</button>
        <button type="button" onclick="changeBodyBg('orange');">Orange</button>
        <label>Change Heading Background To:</label>
        <button type="button" onclick="changeHeadingBg('red');">Red</button>
        <button type="button" onclick="changeHeadingBg('green');">Green</button>
        <button type="button" onclick="changeHeadingBg('blue');">Blue</button>


Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]