How to style DOM elements using JavaScript

By

Published · Updated

Tagged: JavaScript

Learn how to style DOM elements with JavaScript, using classList to add and remove classes or the style property to set inline CSS like color and border.

You might have the need to dynamically apply CSS properties to DOM elements.

What are the APIs browser expose to do that?

First, one of the cleanest ways is to add or remove classes from an element, and use classes styling in your CSS.

const element = document.querySelector('#my-element')

You can use the classList property of an element and its add() and remove() methods:

element.classList.add('myclass')
element.classList.remove('myclass')

You can also directly change each CSS property of an element by using the style property, which references the element inline styles.

For example you can change an element color using

element.style.color = '#fff'

You can alter the border:

element.style.border = '1px solid black'

You saw color and border. You can change all the CSS properties, by using camelCase instead of dashes when the CSS property name contains them.

More classList methods

classList can do more than add and remove.

You can add or remove more than one class at once:

element.classList.add('big', 'highlighted')
element.classList.remove('big', 'highlighted')

toggle() adds the class if it’s missing, and removes it if it’s there. It returns true if the class is now present:

button.addEventListener('click', () => {
  menu.classList.toggle('open')
})

You can pass a second argument to force the result. This is handy when the class depends on a condition:

// add 'error' if the input is empty, remove it otherwise
input.classList.toggle('error', input.value === '')

contains() tells you if the element has a class, and replace() swaps one class for another:

element.classList.contains('open') // true or false
element.classList.replace('light', 'dark')

I use classes for almost everything. The styles stay in the CSS file, and JavaScript only decides which classes are on.

CSS property names in JavaScript

With the style property, a CSS name with dashes becomes camelCase:

CSSJavaScript
background-colorstyle.backgroundColor
font-sizestyle.fontSize
border-top-left-radiusstyle.borderTopLeftRadius
z-indexstyle.zIndex

You can also use the CSS name with brackets:

element.style['background-color'] = 'green'

float is a reserved word, so the property is called cssFloat. Assigning element.style.float also works in current browsers.

Values must be strings with units

Lengths need a unit. A number doesn’t work:

element.style.width = 100 // ignored
element.style.width = '100px' // works

When you set a value the browser doesn’t understand, it’s ignored without any error, and the old value stays:

element.style.color = 'red'
element.style.color = 'notacolor'
element.style.color // 'red'

If a style doesn’t apply and you see no error, check the value first.

Removing a style

Set the property to an empty string:

element.style.color = ''

Or use removeProperty() with the CSS name:

element.style.removeProperty('background-color')

This only removes the inline style. If a CSS rule in your stylesheet sets the same property, that one applies again.

Setting many styles at once

Object.assign() sets several properties and keeps the other inline styles:

Object.assign(element.style, {
  color: 'navy',
  fontWeight: 'bold',
})

cssText replaces the whole style attribute in one go. Any inline style that’s not in the string is removed:

element.style.cssText = 'color: teal; border: 1px solid;'

CSS variables and !important

To set a CSS custom property you must use setProperty(). Assigning element.style['--gap'] does nothing:

element.style.setProperty('--gap', '20px')

Set it on the <html> element to change it for the whole page:

document.documentElement.style.setProperty('--main-color', 'tomato')

Every rule that uses var(--main-color) updates, unless an element sets its own value. I explain how they work in CSS custom properties.

setProperty() also takes a third argument to add !important:

element.style.setProperty('color', 'purple', 'important')

Reading styles: style vs getComputedStyle

element.style only knows about inline styles. It doesn’t see the styles that come from your CSS files.

With this CSS:

#my-element {
  color: red;
}

you get an empty string:

element.style.color // ''

To read the style the element actually has, use getComputedStyle():

getComputedStyle(element).color // 'rgb(255, 0, 0)'
getComputedStyle(element).getPropertyValue('--gap') // '8px'

Computed values are resolved. Colors come back as rgb(), and sizes in pixels. The result is read-only, so you can’t use it to set styles.

Show and hide an element

Set display to none to hide an element, and back to an empty string to restore the value from your CSS:

element.style.display = 'none'
element.style.display = ''

Using '' is better than setting 'block', because the element could be flex, grid or inline in your CSS.

You can find every CSS property in the MDN CSS reference.

Want me to talk about your product? You can sponsor this site.

Related posts about js: