Chapter 6. Element Node Inline Styles

6.1 Style Attribute (a.k.a. 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. In the following code, I am accessing the style attribute of a <div> that contains several inline CSS properties.

Live code

<!DOCTYPE html>
<html lang="en">

<div style="background-color:red;border:1px solid black;height:100px;


var divStyle = document.querySelector('div').style;

//logs 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 (i.e., not the computed styles, which are any styles that have cascaded from stylesheets) are included in the CSSStyleDeclaration object.

6.2 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. In the following code, I set, get, and remove styles on a <div> by manipulating the properties of the style object.

Live code

<!DOCTYPE html> <html lang="en"> <body> <div></div> <script> var divStyle = document.querySelector('div'). ...

Get DOM Enlightenment now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.