The Element.style.cssText property in vanilla JS

The Element.style property is supposed to be a read-only property that returns a CSSStyleDeclaration object: an array of inline style properties the element has, as well as a key/value pair mapping of all available styles you could get or set.
<p id=”app” style=”background-color: rebeccapurple; color: white;”> Hello, world! </p>let app = document.querySelector(‘#app’); // [“background-color”, “color”] let inlineStyles = app.style; But, you’re not supposed to set styles using the property directly.

The Element.style property is supposed to be a read-only property that returns a CSSStyleDeclaration object: an array of inline style properties the element has, as well as a key/value pair mapping of all available styles you could get or set.

<p id="app" style="background-color: rebeccapurple; color: white;">
	Hello, world!
</p>
let app = document.querySelector('#app');

// ["background-color", "color"]
let inlineStyles = app.style;

But, you’re not supposed to set styles using the property directly.

// DON'T do this
app.style = 'font-size: 2em; font-weight: bold;';

I’ve found most browsers will actually let you do it, but it’s not how the property is supposed to work. Instead, you can set individual properties on the Element.style property directly, using a camel-case format.

(_You can find a full list of css-properties and their JS equivalents on MDN._)

// Add styles for font-size and font-weight
app.style.fontSize = '2em';
app.style.fontWeight = 'bold';

But, this weekend, I learned that there’s actually an Element.style.cssText property that works like Element.className, but for inline styles.

You can use it as a getter or setter property.

As a getter, it returns a string with all of the inline styles on an element. When using it to set properties, it will replace all of the styles on the element with whatever you use. It also lets you author styles the way you would plain old CSS.

// returns "background-color: rebeccapurple; color: white;"
let styles = app.style.cssText;

// Wipes out the existing styles and replaces them with this
app.style.cssText = 'font-size: 2em; font-weight: bold;';

// Appends the existing styles with more
app.style.cssText += 'color: rebeccapurple;';

Here’s a demo.

If you need more fine-grained control, targeting individual properties is still a good idea. But if you want easily swap out all of the styles on an element, Element.style.cssText is quite useful!


Print Share Comment Cite Upload Translate
CITATION GOES HERE CITATION GOES HERE
Select a language: