How to Properly Hide and Show Elements Using Javascript

What is the first solution comes to your mind, when someone asks you

How can I dynamically hide any element using Javascript ?

The obvious solutions to this is to set “display” style to “none”. Something like this:

document.getElementById('element').style.display = 'none';

This will surely work, but is it the correct way to do so? May be not, as you would face problems in showing that element again. The problem in showing that element is that you don’t know the original display property of that element. Whether it was a “Block” level element or an “inline” element. So, basically you’ll have to do something like this, depending upon type of element:

document.getElementById('element').style.display = 'block';
document.getElementById('element').style.display = 'inline';

Can we do it in some better way?

Now do it proper way

An improved way to achieve similar thing is to create a css class like this:

.hide{display:none !important;}

And now just add or remove this class to hide and show elements.

document.getElementById('element').className = 'hide';

or write $(“element”).addClass(‘hide’); if you are using mootools.

Leave a Reply