First getElementsByClassName()
literally take the element by class name.
As you have no element with class detalhes
then the function return is an empty array, so when you do el[0].classList
you’re trying to grab the property classList
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/nonexistent object.
According to, toggle("show")
This makes the class alternate show
, that is, if it is not in the add element, if it is already, remove. And it does not exist in the code you posted.
The class details has a display:none
what makes "hide" the element, to show it again need to take 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 case show
that will overwrite/undo this property. The toggle()
will add or remove the class show
which does just that of overwriting/cancelling the display
of the element.
If you look at Chrome’s element inspector, you will see that she appears and disappears confrome the click.
The corrected code would be 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>
At a glance here
– Marco Giovanni
But I wanted to know if there is something wrong with my script, because the article "details" is not being shown?
– Nicolas S.
You set the class
show
and visibility?– Marcelo de Andrade