Open In App

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

Last Updated : 03 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

  • Select the element whose style properties need to be changed.
  • Use element.style property to set the style attribute of an element.
  • Set the properties either by using bracket notation or dash notation.

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

html




<!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 ?

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. 

html




<!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 ?

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads