2

I am fairly new to Java but can't seem to fix this problem;

  • When using getElementsByClassName("") the toggle is not working I get the error "Cannot set property 'display' of undefined"
  • Also when testing this JS with getElementByID("") when double clicking on the English button the text disappeared completely. I want to keep one visible at all time (so either English/ German)

Is there a solution to fix this? Thank you in advance :)

function showHideEnglish() {
  var english = document.getElementsByClassName("text__english");
  var german = document.getElementsByClassName("text__german");
  german.style.display = "none";
  if (english.style.display == "block") {
    english.style.display = "none";
  } else {
    english.style.display = "block";
  }
}

function showHideGerman() {
  var english = document.getElementsByClassName("text__english");
  var german = document.getElementsByClassName("text__german");
  english.style.display = "none";
  if (german.style.display == "block") {
    german.style.display = "none";
  } else {
    german.style.display = "block";
  }
}
<button onclick="return showHideEnglish();">English</button>
<button onclick="return showHideGerman();">German</button>
<div class="text__english" style="display:block;">This text is English</div>
<div class="text__german" style="display:none;">dieser Text ist auf Deutsch</div>
Marcel
  • 193
  • 1
  • 11
  • `getElementsByClassName()` always returns a **list** of elements. You have to operate on each element in the list individually. – Pointy Nov 10 '20 at 14:18
  • https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return – epascarello Nov 10 '20 at 14:25

1 Answers1

2

getElementsByClassName return a a collection of all elements with this class name you need to access the elements inside the list

if you don't have other elements with the same class name this will work

 var english = document.getElementsByClassName("text__english")[0];
  var german = document.getElementsByClassName("text__german")[0];
Ahmed Eid
  • 154
  • 5