0

I have recently started learning javascript and I am trying to do an exercise in which I have to hide a span element with a class inside a paragraph.

But I'm having trouble understanding how I can change the properties and if I'm using the correct method to get the element by its class.

Im getting the next error in console: Uncaught TypeError: Cannot set properties of undefined (setting 'visibility') at muestra (Ej3.js:5:24) at HTMLAnchorElement.onclick (VM28 Ej3.html:17:67)

This my code:

function muestra(){
    var x = document.getElementsByClassName("adicional oculto");
    console.log(x);
    x.style.visibility = "hidden";
}
LoloRG
  • 31
  • 4
  • `x[0].style.visibility = "hidden"` – Barmar Jan 05 '23 at 18:06
  • `getElementByClassName` returns an array like object which means you will have to access to your element by its index. why is that? because there can be more than just one element with the same class. you could also use `var x = document.getElementsByClassName("adicional oculto")[0];` – Chris G Jan 05 '23 at 18:06
  • You could also use `document.querySelector(".adicional.oculto")` That just returns a single element. – Barmar Jan 05 '23 at 18:07
  • [You shouldn't be using the legacy `getElementsByClassName()` in the first place.](https://stackoverflow.com/questions/54952088/how-to-modify-style-to-html-elements-styled-externally-with-css-using-js/54952474#54952474). Use `querySelector(".adicional.oculto")` instead. – Scott Marcus Jan 05 '23 at 18:18
  • It seems that my question was already answered in another post, sorry for the inconvenience. In any case, thanks you very much for all the information and explanations, now I have been able to solve the exercise and the rest of the advice is clear to me. – LoloRG Jan 05 '23 at 18:47

0 Answers0