Learn how to show & hide DOM element using javascript.
We will see 3 different techniques through which we can show or hide the elements using vanilla javascript.
By setting display to none
Every DOM element has style property which we can access to set the display
property.
We can set the display
property to none
to hide the element. Using display:none
will also remove the element from the screen but it will be present in the DOM.
That means the space the element was taking will be removed.
<div id="hideMe" ></div> let elm = document.querySelector('#hideMe'); elm.style.display = 'none';
Similarly we can set the display
property to block
, inline-block
or inline
etc to make it appear again.
elm.style.display = 'block';
By setting visibility to hidden
We can also change the visibility
property of the element to make it hide, It will not remove the element from the screen but instead just disappear the element.
The element space will be still present on the screen.
elm.style.visibility = 'hidden';
We can update the visibility
to visible
to make the element visible again.
elm.style.visibility = 'visible';
By changing opacity to hide the element
The same way we can also change the opacity
of the element to hide it using javascript.
//To hide the element elm.style.opacity = 0; //To show the element elm.style.opacity = 1;