Javascript - Function Hide DIV does not work [closed]

1

Hello

I have a div on my page which is set to (display: none) and clicking on the link hides or displays, but I do not understand 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

    
asked by anonymous 01.10.2016 / 00:39

1 answer

4

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

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

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

Use var esconder = document.getElementById(el); and thus you already have a reference to the element:

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";
    }
}
    
01.10.2016 / 00:42