Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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");
    element.classList.toggle("dark-mode");
 }

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName?retiredLocale=de

So you need to modify your access to the elements:

var elements = document.getElementsByClassName("container-fluid");
if(elements.length === 1) {
   elements[0].classList.toggle("dark-mode");
}

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading