Controlling Appearance

In JavaScript, there are two primary ways to change the design of an element: toggling CSS classes or writing inline styles directly.

1. classList (Highly Recommended)

This is a built-in object that makes adding or removing classes incredibly easy:

  • add("class-name"): Adds a class.
  • remove("class-name"): Removes a class.
  • toggle("class-name"): If the class exists, it removes it. If it doesn't, it adds it.

Let's try hiding the body of the page by adding a Tailwind class (don't worry, you can toggle it back!):

JS Console

Type: document.body.classList.toggle('opacity-0')

(Run it a second time to bring the page back!)

2. The style Property

This allows you to change specific CSS properties directly. It acts as an inline style="..." attribute.

document.body.style.backgroundColor = "red";
Caution

CSS properties with dashes (like background-color) must be written in camelCase in JavaScript: backgroundColor, marginTop, fontSize.

Tip

Always use classList when possible, keeping your visual design inside your CSS files. Only use the style property for dynamic calculations (like updating coordinates while a user is dragging a mouse).