JavaScript in the browser

How to style DOM elements using 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.

Sometimes you need to change how an element looks from JavaScript. I prefer toggling CSS classes and keeping the actual rules in a stylesheet.

Select the element first:

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

Use classList to add or remove class names:

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

When you truly need inline styles, use the style property. It maps to that element’s inline CSS.

Change text color:

element.style.color = '#fff'

Change the border:

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

CSS property names with dashes become camelCase in JavaScript: backgroundColor, not background-color.

See MDN’s CSS properties reference for the full mapping.

Toggle a class on a button click in the console, then set element.style.color = 'tomato'. You should see both approaches apply immediately in the Elements panel.

My default is classes for theme and layout, inline styles only for values you compute at runtime, such as a drag position.

classList.toggle('active') is the method I use most when a button switches state on and off.

Inline styles win over ordinary stylesheet rules because they apply directly on the element. That is another reason I keep layout in CSS files and reach for classList first.

You can read computed styles with getComputedStyle(element), but you cannot set most properties through that object. Use it for inspection, not updates.

For showing and hiding blocks, toggling a hidden class or the hidden attribute is often cleaner than animating inline styles by hand.

element.classList.contains('myclass') lets you branch UI logic without reading computed styles.

Toggle a class on a button in the console, then set element.style.color = 'tomato'. Both changes show up immediately in the Elements panel.

My default is classes for theme, inline styles only for values computed at runtime.

Lesson completed