What error with my script? [closed]

0

I'm new to javascript, and I have this script here:

function mostrar() {
  var el = document.getElementsByClassName("detalhes");
  el[0].classList.toggle("show");
}
.detalhes {
  display: none;
}
<a href="javascript:mostrar();"><h2>'.$linha['nomep'].'</h2></a>

What is going wrong with my script? Because when I click to test, nothing happens?

    
asked by anonymous 05.09.2016 / 21:35

1 answer

2

First getElementsByClassName() literally get the element by the class name.

Since you do not have any element with the class detalhes , the function return is an empty array, so when you do el[0].classList you are trying to get the classList property of item 0, which does not exist Remember that the array is empty?), so the error Cannot read property 'classList' of undefined , js could not read the property of an empty / null / undefined / non-existent object.

Second, toggle("show") this does to change the class show , that is, if it is not in the add element, if it already is, remove. And it does not exist in the code you posted.

The details class has a display:none which makes it "hide" the element, to show it again need to get the display:none could be done by changing the property directly:

el[0].style.display = 'block';

Or as in the example below, add a css class, in the show case that will overwrite / null this property. The toggle() will add or remove the show class, which does just that of overwriting / canceling the display of the element.

If you look at the chrome element inspector, you will see that it appears and disappears clicks.

The corrected code would look like this:

function mostrar() {
  var el = document.getElementsByClassName("detalhes");
  el[0].classList.toggle("show");
}
.detalhes {
  display: none;
}
.show {
  display: block;
}
<a href="javascript:mostrar();"><h2>'.$linha['nomep'].'</h2></a>

<div class="detalhes">Me achou !!!</div>
    
06.09.2016 / 01:24