0

My brain is melting for Why I can't select multiple elements with the same class (querySelector, querySelectorAll, getElementsByClassName, etc) and use classList to check if just one div contains a class.

I've seen tutorials written where it exactly uses getElementsbyClassName as examples, like they work. In my case, on Firefox, it's Uncaught TypeError: document.getElementsByClassName(...).classList is undefined

I'm giving these divs a css class ontoggle -

<div class="dot-container">
   <div class="dot-button" id="1" onclick="activateDot(this.id)"></div>
   <div class="dot-button" id="2" onclick="activateDot(this.id)"></div>
   <div class="dot-button" id="3" onclick="activateDot(this.id)"></div>
   <div class="dot-button" id="4" onclick="activateDot(this.id)"></div>
</div>


function activateDot(id) {
     if(document.getElementsByClassName('dot-button').classList.contains('db-active')) {
        console.log('bruh');
     } else {
        console.log('bruw');
     }
     document.getElementById(id).classList.toggle('db-active');
}

What worked was going -

function activateDot(id) {
   document.getElementById(1).classList.remove('db-active');
   document.getElementById(2).classList.remove('db-active');
   document.getElementById(3).classList.remove('db-active');
   document.getElementById(4).classList.remove('db-active');
   document.getElementById(id).classList.toggle('db-active');
}

Brrrr

Pufty
  • 3
  • 2
  • 1
    The result returned by `getElementsByClassName` doesn't have a `classList` property. That result is not an element, it's a *collection* of elements. You can iterate over that collection and interact with the properties of each element therein. – David Oct 12 '21 at 12:05
  • Allright, thanks. Maybe it's a sign that I'm too stupid for entry level JS, because I still hate how this doesn't work. Still, thanks – Pufty Oct 12 '21 at 12:17

1 Answers1

0

getElementsByClassName returns a list of DOM nodes, while getting an element by ID returns a single element. You need to iterate over the list of elements and add / toggle the desired class for each one of them

Olek Oliynyk
  • 136
  • 3
  • Well, thanks for the quick answer. Couldn't even click that the question was answered this early. Big props for answering a seemingly basic question that my walnut couldn't wrap around – Pufty Oct 12 '21 at 12:19