JavaScript updates element appearance dynamically by toggling CSS classes with element.classList, setting inline CSS properties via element.style, or reading final rendered styles with window.getComputedStyle().
classList Beats Inline element.styleToggling predefined CSS classes via element.classList keeps layout and colors inside your stylesheet where responsive breakpoints, hover states, and dark mode themes belong. Reserve element.style for truly dynamic values computed at runtime, such as drag coordinates or progress indicator percentages.
el.classList.add("open", "active"): Adds one or more classes safely without duplicates.el.classList.remove("open"): Removes specified classes.el.classList.toggle("dark", isDark): Adds or removes based on the optional boolean second argument.el.classList.contains("active"): Checks whether a class is present.getComputedStyle()element.style.color reads inline styles only, so it returns "" for rules coming from external CSS files. Call getComputedStyle(element).color whenever you need the actual rendered value.
const app = document.getElementById("app");
if (app) {
const badge = document.createElement("span");
badge.textContent = "Published";
badge.classList.add("badge", "badge-live");
badge.style.backgroundColor = "#16a34a";
badge.style.padding = "4px 10px";
app.appendChild(badge);
const isLive = badge.classList.toggle("badge-live", true);
const computedBg = getComputedStyle(badge).backgroundColor;
console.log("Classes:", badge.className, "| Live:", isLive);
console.log("Computed background:", computedBg);
}
element.style: el.style.background-color is invalid subtraction in JavaScript. Use camelCase (el.style.backgroundColor) or el.style.setProperty("--accent", "#2563eb") for CSS custom properties.el.className = "active": Assigning className directly wipes out all other utility classes already on the element. Always use classList.box.style.width = 200 is ignored by browsers; include units like "200px" or "50%".--custom-prop) from JavaScript?Use document.documentElement.style.setProperty("--brand-color", "#0ea5e9"), because dot notation cannot access property names starting with --.
classList.toggle("hidden", shouldHide) do?Passing a boolean forces the class to be added when true and removed when false, preventing toggle state from drifting out of sync.
getComputedStyle() allow writing styles?No, getComputedStyle(el) returns a read-only style declaration object; modify styles via classList or el.style.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.