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.
<!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.
<!DOCTYPE html> <html lang="en"> <body> <div></div> <script> var divStyle = document.querySelector('div'). ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access