Episode 13 of 18

Styles & Classes

Modify element styles and CSS classes dynamically — use the style property for inline styles and classList for toggling classes.

Styles & Classes

JavaScript can change how elements look by modifying inline styles or toggling CSS classes. Classes are the preferred approach — they keep styling in CSS where it belongs.

Inline Styles

var title = document.querySelector('h1');

title.style.color = 'crimson';
title.style.fontSize = '3rem';
title.style.marginTop = '20px';
title.style.backgroundColor = '#f4f4f4';

CSS properties with hyphens (like font-size) become camelCase in JavaScript (fontSize). Inline styles have the highest specificity — they override stylesheet rules.

Reading Styles

// Only reads inline styles set via JavaScript
console.log(title.style.color); // "crimson"

// Reads the final computed style (all sources)
var computed = getComputedStyle(title);
console.log(computed.fontSize); // "48px" (resolved value)

classList

var box = document.querySelector('.box');

box.classList.add('active');       // Add a class
box.classList.remove('active');    // Remove a class
box.classList.toggle('active');    // Toggle — add if missing, remove if present
box.classList.contains('active'); // Returns true or false
box.classList.replace('old', 'new'); // Replace one class with another

classList vs className

PropertyTypeEffect
classNameStringReplaces all classes: el.className = 'a b'
classListDOMTokenListAdd, remove, toggle individual classes

classList is preferred because it does not accidentally overwrite existing classes.

Practical Example

var items = document.querySelectorAll('li');

items.forEach(function(item) {
    item.addEventListener('click', function() {
        this.classList.toggle('completed');
    });
});

// CSS:
// .completed { text-decoration: line-through; opacity: 0.5; }

Key Takeaways

  • Use element.style.property for inline styles (camelCase property names)
  • getComputedStyle() reads the final resolved style from all sources
  • classList.add/remove/toggle is the preferred way to manage CSS classes
  • Keep styling in CSS and toggle classes from JavaScript for clean separation