How to toggle a class in DOM

How to toggle a class in DOM, i want to make a dark mode toggle in class container-fluid

function DarkModeToggle() {
    var element = document.getElementsByClassName("container-fluid");

and get this error

Uncaught TypeError: Cannot read properties of undefined (reading 'toggle')
    at DarkModeToggle (main.js:4:21)
    at HTMLButtonElement.onclick (index.html:26:46)

any solution to add a class and toggle it

>Solution :

As the name says getElementsByClassName() function is not returning one element instead returning an array of matching elements! Of course if the class name matches to only one element, there will be only one element in the array.

See also the docs:

So you need to modify your access to the elements:

var elements = document.getElementsByClassName("container-fluid");
if(elements.length === 1) {

The code above is expecting / checking if there is only one result. If you expect more results, you need to do a i.e. for loop to modify all.

Leave a Reply