Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a 'toggle class' function in vanilla JavaScript?

Tags:

javascript

This function should search the document for any element with a 'data-info' attribute with a value of 'graphicDesign' then toggle the class 'hideMe' on those elements.

It returns the correct amount of elements in the console, but breaks on the classList toggle.

I've tried alternatives such as finding elements by class name then toggling, but this doesn't work either.

function toggleGraphicDesign() {
    let graphicDesignElements = document.querySelectorAll('[data-info="graphicDesign"]');
    console.log(graphicDesignElements.length);

    graphicDesignElements.classList.toggle('hideMe');

}
like image 760
LinkTCOne Avatar asked Oct 24 '25 08:10

LinkTCOne


1 Answers

querySelectorAll() return a NodeList not a single element.According to MDN

The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.

You need to loop through all the elements using forEach() and toggle class of each element.

function toggleGraphicDesign() {
    let graphicDesignElements = document.querySelectorAll('[data-info="graphicDesign"]');
    console.log(graphicDesignElements.length);
    graphicDesignElements.forEach(x => x.classList.toggle('hideMe')) 
}
like image 193
Maheer Ali Avatar answered Oct 26 '25 21:10

Maheer Ali