How to add/remove CSS inline-style with the DOM

About

This page talks about on how to manipulate the HTML style attribute on the DOM.

This page is part of CSS javascript serie: CSS - Javascript Manipulation

Example

Set

To set an inline style, you use:

  • the qualified method: element.style.setProperty method of an element
element.style.setProperty(property, value, priority);

// example
element.style.setProperty('color', 'purple', 'important')
  • or the shortcut that will set the attribute to a low priority
button.style.color = "purple";

Demo:

<button style="color: blue">Click to change my color</button>
document.querySelector('button').addEventListener("click", function(event) { 
    button  = event.target;
    color = button.style.color;
    if(color=="blue"){
       // qualified  method
        button.style.setProperty('color',"purple","important");
    } else {
        // property set method
        button.style.color = "blue";
    }
});
  • Click on the button to see it in action

Get

  • The property value or an empty string if not set
value = el.style.getPropertyValue('cssProperty');
  • The priority value or an empty string if not set
priority = el.style.getPropertyPriority('cssProperty');





Discover More
Class Html Beauty Blue Added
DOM - Class attribute

manipulation in the DOM. API The DOM Web API has a special function to select on class: the getElementsByClassName() function one You can select the class with a selector With Native Javascript...



Share this page:
Follow us:
Task Runner