0

I try to add a class called "finished" as soon as an event is fired. I'm trying to achieve this with classList.toggle() but somehow, it doesn't work. Here's my code:

let checked = document.getElementsByClassName("single-note");
checked.classList.toggle("finished");

Testing it in the console, checked works and gives me back the elements. But toggle doesn't add any classes, it shows "Uncaught TypeError: Cannot read property 'toggle' of undefined". I also already tried it with .add and .contains, but this doesn't work either, giving me the same error message. I know it must have something to do with classList, but I don't know what I'm missing out.

  • `document.getElementsByClassName("single-note")[0];` – Thielicious Oct 23 '17 at 10:04
  • You could change `document.getElementsByClassName("single-note");` to `let checked = document.querySelector(".single-note");`. That would solve the issue. –  Oct 23 '17 at 10:05
  • @Simon .querySelector only adresses the first occurence, doesn't it? But I want to get all the divs with that classname. – newbiecoder Oct 23 '17 at 10:26
  • It will only affect the first instance. To get all instances you could use something like this `let checked = document.querySelectorAll(".single-note"); Array.prototype.forEach.call(checked, function(el, i){ el.classList.toggle("finished"); });` –  Oct 23 '17 at 10:34

0 Answers0