classList, & Computed StylesJavaScript can dynamically manipulate element styling using the inline element.style property, manage CSS classes via element.classList, or inspect resolved styles using window.getComputedStyle().
flowchart TD
StylingReq["Dynamic Styling Requirement"] --> Choice{"Style Management Strategy?"}
Choice -- "Toggle Predefined CSS Classes" --> ClassList["element.classList (add, remove, toggle, replace)"]
Choice -- "Dynamic Calculated Dimensions / Colors" --> InlineStyle["element.style.setProperty()"]
Choice -- "Read Rendered Computed Styles" --> Computed["window.getComputedStyle(element)"]
| API | Code Example | Primary Purpose |
|---|---|---|
classList.add() |
el.classList.add("active", "visible") |
Adds CSS classes to element. |
classList.remove() |
el.classList.remove("hidden") |
Removes CSS classes. |
classList.toggle() |
el.classList.toggle("dark-mode") |
Toggles class existence (returns boolean). |
element.style |
el.style.backgroundColor = "blue" |
Sets inline CSS style property (camelCase). |
getComputedStyle() |
window.getComputedStyle(el).width |
Reads resolved, computed pixel styles from stylesheet. |
// Demonstrating classList, inline styles, and getComputedStyle
document.addEventListener("DOMContentLoaded", () => {
const card = document.createElement("div");
card.className = "card-container";
card.textContent = "Interactive Styling Card";
document.body.appendChild(card);
// 1. Managing Classes via classList API
card.classList.add("shadow-lg", "p-4");
console.log(`Has class 'p-4'? ${card.classList.contains("p-4")}`); // true
card.classList.toggle("active"); // Adds "active"
console.log(`Classes after toggle: ${card.className}`);
// 2. Direct Inline Style Assignment (camelCase properties)
card.style.backgroundColor = "#1e293b";
card.style.color = "#ffffff";
card.style.borderRadius = "8px";
// 3. Inspecting Resolved Computed Styles (getComputedStyle)
const computedStyles = window.getComputedStyle(card);
console.log(`Computed Background Color: ${computedStyles.backgroundColor}`);
console.log(`Computed Resolved Display: ${computedStyles.display}`);
});
classList Over Inline element.style: Keep CSS presentation rules in external stylesheets and use JavaScript to toggle CSS class names.background-color) become camelCase in JavaScript (element.style.backgroundColor).element.style Only Reads Inline Styles: Reading element.style.color returns an empty string if the color was set in an external CSS file. Use window.getComputedStyle(element).color to read actual rendered colors.What is the difference between element.style.width and window.getComputedStyle(element).width?
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.