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">
<body>

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

<script>

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

//logs CSSStyleDeclaration {0="background-color", ...}
console.log(divStyle);

 </script>
</body>
</html>

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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.