Change Style of HTML Element using JavaScript

In this tutorial, we shall learn to change style of HTML Element programmatically using HTMLElement.style.

Syntax

The syntax to change style of a HTML element dynamically using JavaScript is

HTMLElement.style="styling_data"

Change Style of Element via getElementById

A simple code snippet to change the style of an element whose id is message is

document.getElementById("message").style="color:#f00;padding:5px;"

Any styling properties supported by the HTML Element can be supplied in the assigned value, just like inline style CSS.

In the following example, we shall get reference to an HTML DOM Element using document.getElementById() method, and change its style value.

index.html

<!doctype html>
<html>
<body>
    <h1>JavaScript HTMLElement.style Example</h1>
    <p id="message">This is a paragraph.</p>
    <script>
        <!-- your JavaScript goes here -->
        var messageElement = document.getElementById("message");
        <!-- try changing the styles and run -->
        messageElement.style="color:#090;border:1px solid #aaa;text-align:center;";
    </script>
</body>
</html>

Change Style of Element via getElementsByClassName

In the following example, we shall get reference to an HTML DOM Elements using document.getElementsByClassName() method, and change their style value,

index.html

<!doctype html>
<html>
<body>
    <h1>JavaScript HTMLElement.style Example</h1>
    <p class="message">This is a paragraph.</p>
    <p class="message">This is another paragraph.</p>
    <script>
        <!-- your JavaScript goes here -->
        var x = document.getElementsByClassName("message");
        <!-- try changing the styles and run -->
        for (i = 0; i < x.length; i++) {
            x[i].style = "padding:20px;border:1px solid #bbb;";
        } 
    </script>
</body>
</html>

Conclusion

In this JavaScript Tutorial, we have learnt to change style of HTML Element dynamically using HTMLElement.style, with the help of Try Online Examples.