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
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
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.