Rahmat
Rahmat

Reputation: 3

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

Upvotes: 0

Views: 75

Answers (1)

dns_nx
dns_nx

Reputation: 3953

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.

Upvotes: 1

Related Questions