What’s wrong with my script?

Asked

Viewed 78 times

0

I’m kind of new with 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’s going wrong with my script? Because when I click to test, nothing happens?

  • At a glance here

  • But I wanted to know if there is something wrong with my script, because the article "details" is not being shown?

  • You set the class show and visibility?

1 answer

2


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 showthat will overwrite/undo this property. The toggle() will add or remove the class showwhich does just that of overwriting/cancelling the displayof 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>

  • Hello friend! Thank you for answering. But yes, I already have a div with the details class just like in your example. I just didn’t understand where by that class="show".

  • I edited an answer explaining a landing on this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.