JAVASCRIPT

Toggle CSS Class on Multiple Elements for Styling

Discover how to efficiently select multiple DOM elements and toggle a specific CSS class on them, enabling dynamic styling changes like active states or visibility with minimal code.

function toggleClassOnElements(selector, className) {
    const elements = document.querySelectorAll(selector);
    elements.forEach(element => {
        element.classList.toggle(className);
    });
}

// Usage example:
// Assuming you have elements like <li class="item">...</li>
// <style>.active { background-color: yellow; }</style>
// toggleClassOnElements('.item', 'active'); // Toggles 'active' class on all '.item' elements

// To add a class:
// document.querySelectorAll('.item').forEach(el => el.classList.add('highlight'));

// To remove a class:
// document.querySelectorAll('.item').forEach(el => el.classList.remove('highlight'));
How it works: This snippet provides a function to select multiple DOM elements using a CSS selector and then iterate over them to toggle a specified CSS class. This is an efficient method for applying or removing styling based on user interaction or application state, relying on pre-defined CSS rules for visual changes rather than direct inline style manipulation.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs