Categories
JavaScript Answers

How to change element style attribute dynamically using JavaScript?

Spread the love

To change element style attribute dynamically using JavaScript, we call the style.setProperty method.

For instance, we write

document.getElementById("abc").style.setProperty("padding-top", "10px");
document
  .getElementById("abc")
  .style.setProperty("padding-top", "10px", "important");

to select the eleemnt with getElementByid.

And then we call style.setProperty with the property name, value, and optionally, the 'important' string as the 3rd argument.

"important" adds the !important directive.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *