JS Tip of the Day: Setting HTML Element Styles

Setting HTML Element Styles
Level: Beginner

In JavaScript, you can set css styles for an element using its style property. This mirrors the style attribute in HTML but with a couple of important differences.

First, the style property is an object in JavaScript, not a string value as it is in the HTML attribute. This object is a CSSStyleDeclaration object with each of the individual style declarations defined as properties of that object.

<div id="warning" style="color: red">
Danger, Will Robinson!
</div>

<script>
let warning = document.getElementById('warning');
console.log(typeof warning.style); // object
console.log(warning.style.color); // red
</script>

You can access the string representation of the style if you want through the cssText property of style. This can also be set. Doing so would be equivalent to setting the style attribute.

<div id="warning" style="color: red">
Danger, Will Robinson!
</div>

<script>
let warning = document.getElementById('warning');
console.log(warning.style.cssText); // color: red
warning.style.cssText = 'color: orange';
console.log(warning.getAttribute('style')); // color: orange
</script>

Secondly, you can access declaration property names by their camelCase names rather than their hyphen-case names. For example, margin-left in the style object would be accessible as style.marginLeft.

<blockquote id="indented" style="margin-left: 2em">
640K ought to be enough for anybody.
</blockquote>

<script>
let indented = document.getElementById('indented');
console.log(indented.style.marginLeft); // 2em
indented.style.marginLeft = '5px';
console.log(indented.style.marginLeft); // 5px
</script>

Notice that the values being used for CSS measurements is a string which includes the numeric value and a unit. If you need to get a number value from the CSS, you may need to parse the string into a number first being sure to make the appropriate conversions for the units specified.

Lastly, if you need to remove a declaration, you can set its property to an empty string. Using the delete keyword will not work. You can also optionally use the removeProperty() method, though you’ll want to be sure to use the hyphen-case name of the property you’re removing.

<span id="stylish" style="font-weight: bold; font-style: italic">
Stylish!
</span>

<script>
let stylish = document.getElementById('stylish');
stylish.style.fontWeight = ''; // removes
stylish.style.removeProperty('font-style'); // also removes
console.log(stylish.style.cssText === ''); // true (no properties)
</script>

A setProperty() method also exists for adding or changing declarations, though its usually easier to set the respective properties directly by name.

More info: