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:
- The button that when clicked will change its text color
<button style="color: blue">Click to change my color</button>
- We select the first button, add event listener that execute a callback function using the target element (ie the button) to change the style
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');