Open In App

How to change style attribute of an element dynamically using JavaScript ?

Given an HTML document and the task is to change the style properties (CSS Properties) of an element dynamically with the help of JavaScript.

Approach: Using element.style Property

The element.style property is represented by the CSSStyleDeclaration object, which is returned via the style property.



Example 1: This example changes the color and background color of the heading element.




<!DOCTYPE html>
<html>
 
<body>
    <h1 id="h1" style="color:green;">
        GeeksforGeeks
    </h1>
 
    <p>
        Click on the button to change
        the style attribute
    </p>
 
    <button onclick="gfg_Run()">
        Click here
    </button>
 
    <p id="result"></p>
 
    <script>
        let res = document.getElementById("result");
        let heading = document.getElementById("h1");
 
        function gfg_Run() {
            heading.style["background-color"] = "green";
            heading.style["color"] = "white";
            res.innerHTML = "Style Attribute Changed";
        }       
    </script>
</body>
 
</html>

Output



How to change style attribute of an element dynamically using JavaScript ?

Example 2: This example changes the color, background color, and width properties of elements. 




<!DOCTYPE html>
<html>
 
<body>
    <h1 id="h1" style="color:green;">
        GeeksforGeeks
    </h1>
 
    <p id="para">
        Click on the button to change
        the style attribute
    </p>
 
    <button onclick="gfg_Run()">
        Click here
    </button>
 
    <p id="result"></p>
 
    <script>
        let heading = document.getElementById("h1");
        let para = document.getElementById("para");
        let res = document.getElementById("result");
 
        function gfg_Run() {
            heading.style["color"] = "white";
            heading.style["background-color"] = "green";
            heading.style["width"] = "300px";
            heading.style["border"] = "1px solid black";
 
            para.style["background-color"] = "green";
            para.style["width"] = "400px";
            para.style["border"] = "1px solid black";
 
            res.innerHTML = "Style Attribute Changed";
        }       
    </script>
</body>
 
</html>

Output:

How to change style attribute of an element dynamically using JavaScript ?


Article Tags :