Element Node Inline Styles

Element Node Inline Styles

Style Attribute (Element Inline CSS Properties) Overview

Every HTML element has a style attribute that can be used to insert inline CSS properties specific to the element

<div class="box" style="background:black;height:100px;width:100px;"></div>  
var box = document.querySelector('.box');  
console.log(box.style);//CSSStyleDeclaration {0="background-color", ...}  

Notice in the code that the style property returns a CSSStyleDeclaration object and not a string. Additionally, note that only the element’s inline styles are included in the CSSStyleDeclaration object.

Getting, Setting, and Removing Individual Inline CSS Properties

Inline CSS styles are individually represented as a property (i.e., an object property) of the style object available on element node objects. This provides the interface for us to get, set, or remove individual CSS properties on an element by simply setting an object’s property value.

<div class="box" style="background:black;height:100px;width:100px;"></div>  
var boxStyle = document.querySelector('.box').style;  
boxStyle.backgroundColor = 'red';  
boxStyle.backgroundColor = '';  

The style object is a CSSStyleDeclaration object and it provides access not only to individual CSS properties, but also to the setPropertyValue(propertyName), getPropertyValue(propertyName,value), and removeProperty() methods used to manipulate individual CSS properties on an element node.


Set CSS use csstext

Using the cssText property of the CSSStyleDeclaration object, as well as the getAttribute() and setAttribute() methods, it’s possible to get, set, and remove the entire value (i.e., all inline CSS properties) of the style attribute using a JavaScript string.

var boxStyle = document.querySelector('.box').style;  
boxStyle.cssText = 'background-color:blue;height:100px;width:100px;';  
console.log(boxStyle.cssText);//background-color: blue; height: 100px; width: 100px;  
boxStyle.cssText = '';//""