0

Here's my entire js code:

var htmlLang = document.documentElement.getAttribute("lang");
var en = document.getElementsByClassName("en");
var es = document.getElementsByClassName("es");

if(htmlLang == "en"){
    es.style.display = "none";
} else if(htmlLang == "es"){
    en.style.display = "none";
}

And here are the HTML elements I'm trying to modify:

<td><a href='register.php'><span class='en'>Register</span><span class='es'>Registrar</span></a></td>
<td><a href='about.php'><span class='en'>About Me</span><span class='es'>Sobre mi</span></a></td>
<td><a href='login.php'><span class='en'>Log In</span><span class='es'>Iniciar sesi&otilde;n</span></a></td>

When I launch the page, I get the error:

Uncaught TypeError: Cannot set property 'display' of undefined at main.js:6 < Which is at the "es.style..." in the js.

To me everything looks right and I thought it had to do with scope, but putting the whole variable (document.getElements...) in the if statement I get the same error.

Thanks to anyone who can help!

Noah W
  • 11
  • 1
  • 3

1 Answers1

0

When you select items with document.getElementByClassName you will get a Collection List of all elements found so you wont be able to change the styles on it. So convert it to an array Array.from(document.getElementByClassName("es"))

Here is a working edit i made:

var htmlLang = document.documentElement.getAttribute("lang");
var en = Array.from(document.getElementsByClassName("en"));
var es = Array.from(document.getElementsByClassName("es"));


if(htmlLang == "en"){
    es.forEach(e => {
      e.style.display = "none"
    })
} else if(htmlLang == "es"){
    es.forEach(e => {
      e.style.display = "none"
    })
}
Mohamed Ali
  • 141
  • 1
  • 6
  • THANK YOU SO MUCH! I appreciate the comment especially considering this question seems to have been asked already. I had no idea about that with the class elements. Great to know! – Noah W Jun 28 '20 at 01:14