How to style DOM elements using JavaScript

A way to dynamically apply styles to page elements using pure JavaScript

You may need to apply CSS properties to DOM elements dynamically.

What APIs does the browser expose?

First of all, one of the cleanest methods is to add or remove classes from elements and use class styles in CSS.

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

you can use itclassListElements and their attributesadd()withremove()method:

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

You can also use to directly change each CSS property of an element.styleAttribute, it refers to the elementInline style.

For example, you can use

element.style.color = '#fff'

You can change the border:

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

you saw itcolorwithborder. You can change all CSS properties by using camelCase instead of dashes (when CSS property names include them).

The translation table can be conveniently listed in the following locations:This MDN page.

Download mine for freeJavaScript beginner's manual


More js tutorials: