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"
Try Online

In the following example, we are changing the style of an element whose id is message.

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

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

Example 1 – Change Style of Element

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

var messageElement = document.getElementById("message");
messageElement.style="color:#090;border:1px solid #aaa;text-align:center;";
Try Online

Try Online

Example 2 – Change Style of Element using JS

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

<!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>
Try Online

Try Online

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.