Changing Styles & Classes
Overview
You can modify the visual appearance of an element dynamically using JavaScript. There are two ways to do this:
1. Inline Styles: Modifying the .style property directly.
2. Class List: Adding or removing CSS classes (Highly Preferred!).
Modifying the classList is the professional standard because it keeps your styling logic inside your CSS files, and your behavior logic inside JS.
Syntax
const box = document.querySelector('.box');
// Add a class
box.classList.add('active');
// Remove a class
box.classList.remove('hidden');
// Toggle (Adds if missing, removes if present)
box.classList.toggle('dark-mode');
// Check if a class exists (Returns boolean)
const isActive = box.classList.contains('active');const box = document.querySelector('.box');
// CSS properties with hyphens become camelCase in JS!
// 'background-color' becomes 'backgroundColor'
box.style.backgroundColor = "red";
box.style.marginTop = "20px";Common Pitfalls
- Forgetting to use camelCase for inline styles. Trying to write
box.style.background-color = 'red'will cause a Syntax Error because JavaScript interprets the hyphen as a subtraction operator. It must bebox.style.backgroundColor.
Interview Questions
classList preferred over modifying .style directly?Modifying .style injects inline styles into the HTML, which is hard to maintain, overrides CSS stylesheets, and causes performance issues if done heavily. Using classList maintains a clean Separation of Concerns (CSS handles look, JS handles state).
Real-World Example
Creating a toggle button for Dark Mode.
themeBtn.addEventListener('click', () => {
document.body.classList.toggle('dark-theme');
});Check Your Knowledge
Test your understanding of Changing Styles & Classes with these quick questions.