LESSON 26
Changing Styles
Learning objective: Modify element styles and classes with JavaScript.
Understand
JavaScript can restyle elements on the fly.
You can set inline styles with element.style.color, but the cleaner approach is toggling CSS classes with classList.add, remove, and toggle. Keeping styling in CSS classes keeps your code tidy.
Analogy: Toggling a class is like flipping an outfit on or off rather than restitching the clothes.
See It in Action
Toggling a class:
const box = document.querySelector(".box");
box.classList.toggle("active");How it works:
toggle adds the active class if missing and removes it if present — perfect for on/off UI states.Try It Yourself
- Change an element's color with
.style. - Add a class with
classList.add. - Toggle a class on and off.
Quick Quiz
Why prefer classList over inline styles?
Challenge
Toggle a highlight class on an element with JavaScript.
Success condition: Running your code visibly toggles the element's style.
+10 XP
Lesson Complete
You answered correctly and completed the required practice. Your progress has been saved on this device.
Continue to next lesson →