1

I have a div element with 2 classes that I would like to toggle a third class on depending on whether another element is active.

The other element's 'active' class is working, but I cannot work out how to toggle 'class3' on an element - I am getting the error

Uncaught TypeError: Cannot read property 'toggle' of undefined

but I am unsure exactly what about this function is incorrect. I'm still learning so this may be obvious!

HTML:

<div class="class1 class2"></div>

JS:

document.getElementById("button").addEventListener("click", 
myFunction); 

function myFunction(){

if (document.getElementById("otherElement").classList.contains("active")){
 document.getElementsByClassName("class2").classList.toggle("class3");
}}

I also want to do this in pure JS, even if jQuery may be easier just to learn from the ground up

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
impi
  • 13
  • 3
  • The [docs](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName) are your friend. You should read them. `getElementsByClassName` does not return an element. – gforce301 Apr 17 '18 at 14:48

2 Answers2

0

getElementsByClassName return an HTMLCollection, an array even if there's only one element with that class, add [0] to select the first one and toggle the class3

document.getElementById("button").addEventListener("click", 
myFunction); 

function myFunction(){

if (document.getElementById("otherElement").classList.contains("active")){
 document.getElementsByClassName("class2")[0].classList.toggle("class3");
}}
.class1{
  background: red;
}

.class2{
  background: blue;
}

.class3{
  background: green;
}

div{
  width: 100px;
  height: 50px;
}
<div class="class1 class2">hello</div>
<div id="otherElement" class="active">
there
</div>
<button id="button">
click
</button>
Taki
  • 17,320
  • 4
  • 26
  • 47
0

document.getElementsByClassName("class2") returns an array. You'll need to loop through each index of it.

if (document.getElementById("otherElement").classList.contains("active")){
  const size = document.getElementsByClassName("post-text").length;
  
  if (size > 0) {
   for (let i = 0; i < size; i++){
      document.getElementsByClassName("post-text")[i].classList.toggle("class3");
   }
  }
  
}
mrchaarlie
  • 374
  • 2
  • 11
  • Thank you, this worked perfectly! I hadn't even considered I wold need to loop through it – impi Apr 17 '18 at 15:18