JavaScript > DOM Manipulation > Modifying Elements > classList methods

Toggle Dark Mode with classList

This code snippet demonstrates how to use the classList methods in JavaScript to toggle a dark mode theme on a website. It covers adding, removing, and toggling CSS classes to dynamically change the appearance of elements.

Initial HTML Setup

This HTML code sets up a basic webpage with a button to toggle dark mode and some sample text. The CSS includes styles for both light and dark modes, with a transition for a smooth effect.

<!DOCTYPE html>
<html>
<head>
    <title>Dark Mode Toggle</title>
    <style>
        body {
            background-color: white;
            color: black;
            transition: background-color 0.3s ease, color 0.3s ease;
        }
        body.dark-mode {
            background-color: black;
            color: white;
        }
        button {
            padding: 10px 20px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <button id="darkModeToggle">Toggle Dark Mode</button>
    <p>This is some sample text to demonstrate the dark mode functionality.</p>
    <script src="script.js"></script>
</body>
</html>

JavaScript Logic with classList

This JavaScript code retrieves the button and body elements. It then adds an event listener to the button that toggles the 'dark-mode' class on the body element using classList.toggle(). The button text is also dynamically updated to reflect the current mode. classList.contains() checks for the presence of the class.

// script.js
const darkModeToggle = document.getElementById('darkModeToggle');
const body = document.body;

darkModeToggle.addEventListener('click', () => {
    body.classList.toggle('dark-mode');

    // Update button text based on current mode
    if (body.classList.contains('dark-mode')) {
        darkModeToggle.textContent = 'Disable Dark Mode';
    } else {
        darkModeToggle.textContent = 'Enable Dark Mode';
    }
});

Concepts Behind the Snippet

The classList property is a read-only property that returns a live DOMTokenList representing the class attribute of the element. It provides methods like add(), remove(), toggle(), and contains() to manipulate the CSS classes of an element. This allows for dynamic styling of web pages using JavaScript without directly manipulating the element's className property, which can be more cumbersome.

Real-Life Use Case

Dark mode toggles are a common feature on modern websites and applications. They allow users to switch between light and dark themes based on their preferences or environmental conditions (e.g., reducing eye strain in low-light environments). This snippet provides a simple, functional implementation of this feature.

Best Practices

  • Use descriptive class names (e.g., 'dark-mode' instead of 'dm').
  • Ensure your CSS provides appropriate styles for both states (light and dark mode).
  • Consider using CSS variables (custom properties) to manage color palettes and make theme switching more efficient.
  • Store the user's preference (e.g., in local storage) to persist the theme across sessions.

Interview Tip

When discussing classList in an interview, highlight its advantages over directly manipulating the className property. Explain how it provides a more structured and efficient way to add, remove, and toggle CSS classes. Also, be prepared to discuss the browser compatibility of classList (it's widely supported, but older browsers might require polyfills).

When to Use Them

Use classList methods whenever you need to dynamically modify the CSS classes of an element in response to user interactions, data changes, or other events. They are particularly useful for implementing features like toggling themes, highlighting active elements, and applying conditional styling.

Memory footprint

The memory footprint of using classList is generally low. It creates a DOMTokenList object, which is relatively lightweight. However, excessive DOM manipulation, including frequent class modifications, can potentially impact performance, especially on complex pages. Optimize your code by minimizing unnecessary DOM updates and using techniques like debouncing or throttling when handling frequent events.

Alternatives

The main alternative to classList is directly manipulating the className property of an element. However, this approach can be more error-prone and less efficient. You can also use libraries or frameworks like jQuery or React, which provide their own methods for manipulating CSS classes. However, using native classList methods is generally preferred for modern JavaScript development.

Pros

  • More readable and maintainable code compared to direct className manipulation.
  • Provides a structured API for adding, removing, and toggling classes.
  • Avoids potential issues with overwriting existing classes.
  • Generally more efficient than direct className manipulation.

Cons

  • Slightly less performant than directly setting className if only setting classes, but the difference is often negligible.
  • Requires understanding of the DOMTokenList interface.

FAQ

  • What if I need to support older browsers that don't support classList?

    You can use a polyfill to provide classList functionality in older browsers. A polyfill is a piece of code that provides the functionality that a browser doesn't natively support.
  • Can I use classList to add multiple classes at once?

    Yes, the add() and remove() methods can accept multiple class names separated by commas: element.classList.add('class1', 'class2', 'class3');
  • How does classList.toggle() work?

    The toggle() method adds the class if it's not present and removes it if it is. You can also pass a second argument to toggle(), which is a boolean value that forces the class to be added (if true) or removed (if false).