Javascript - Hide DIV function does not work

Asked

Viewed 146 times

1

Hello

I have a div on my page that is defined as ( display: None ) and when clicking on the link hides or displays, but I’m not understanding why my function is not working.

Code:

function esconder(el)
{
  var esconder = document.getElementById(el).style.display;
  if(esconder == "none")
    {
     alert("Exibir: " + el);
     esconder.style.display = "block";
    }
   else
    {
     alert("Esconder: " + el);
     esconder.style.display = "none";
    }
}

Thank you

1 answer

4


You have a problem with your code, esconder is not a reference to the element, but a string with the state of the display.

That is, the line var esconder = document.getElementById(el).style.display; will cause esconder be a string with "none" or "block" and so you can’t use esconder.style.display = "block";, because it would be the same as

"none".style.display = "block";

Usa var esconder = document.getElementById(el); and so you already have a reference to the:

function esconder(el) {
    var esconder = document.getElementById(el);
    if (esconder.style.display == "none") {
        alert("Exibir: " + el);
        esconder.style.display = "block";
    } else {
        alert("Esconder: " + el);
        esconder.style.display = "none";
    }
}
  • Thank you very much Sergio, but I did not understand your explanation very well.

  • 2

    @abduzeedo what he said is that when you did it var esconder = document.getElementById(el).style.display; and tried to spin it after esconder.style.display = "block"; would be the same as doing this: document.getElementById(el).style.display.style.display = "block";, that is wrong.

  • @abduzeedo added a more detailed explanation.

  • 1

    Perfect, now I understand, it really didn’t make sense my code, thank you

Browser other questions tagged

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