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;" >         neveropen     </ 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.Â
html
<!DOCTYPE html> < html > Â
< body >     < h1 id = "h1" style = "color:green;" >         neveropen     </ 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 ?