-1

The following code is producing an error for me

tab.addEventListener("click", (e) => { 
  e.preventDefault();
  if (document.getElementsByTagName("a").classList.contains("active")) {
    document.getElementsByTagName("a").classList.remove("active"); 
  } else {
    console.log("nothing")
  }
}) 

It is producing this error in the console.

Uncaught TypeError: Cannot read properties of undefined (reading 'contains')

I am confused, because I am not sure why this error is happening. Even stranger, when the classList.remove("active") is outside of the conditional, the same error occurs, with contains replaced with add. Can someone explain to me why this error is happening?

Thank you

jeremy_lord
  • 469
  • 7
  • 23
  • [`getElementsByTagName`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName) returns a live HTML collection of elements. You can't use `classList` on it. If you're picking up all the anchors you'll need [to iterate over the collection](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration), and check and set the classList of each element separately. – Andy Oct 31 '21 at 08:16

1 Answers1

-2
document.getElementsByTagName("a")

returns an array

.classList will be undefined on an array

So when you try to access the contains() method you get the error that you are seeing.

A solution would be to use a filter and for each on the array.