Borislav Hadzhiev
Thu Jan 06 2022·2 min read
Photo by Drew Coffman
To show/hide a div element by id:
style.display
property on the div
element.display
property is set to none
, set it to block
.none
.Here is the HTML for the examples in this article.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box" style="background-color: salmon; width: 100px; height: 100px"> Box 1 </div> <button id="btn">Hide div</button> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const box = document.getElementById('box'); const btn = document.getElementById('btn'); btn.addEventListener('click', function handleClick() { if (box.style.display === 'none') { box.style.display = 'block'; btn.textContent = 'Hide div'; } else { box.style.display = 'none'; btn.textContent = 'Show div'; } });
We selected the div
by its id using the
document.getElementById
method.
Then, we added a click
event listener to the button. Every time the button is
clicked, the handleClick()
function is invoked.
In the function, we check if the button's display
CSS property has a value of
none
.
display
value set to none
, then it is hidden, in which case, we set its display
value to block
to show the element.Otherwise, the div
is shown, in which case we set its display
value to
none
to hide it.
We also used the textContent
property, to update the button's text when the
div
is hidden / shown.
We used the display property in the examples, however you might need to use the visibility property depending on your use case.
display
property is set to none
, the element is removed from the DOM and has no effect on the layout. The document is rendered as though the element does not exist.On the other hand, when an element's visibility property is set to hidden, it still takes up space on the page, however the element is invisible (not drawn). It still affects the layout on your page as normal.
Here is an example that uses the visibility
property to show/hide a div
element by its id.
const box = document.getElementById('box'); const btn = document.getElementById('btn'); btn.addEventListener('click', function handleClick() { if (box.style.visibility === 'hidden') { box.style.visibility = 'visible'; btn.textContent = 'Hide div'; } else { box.style.visibility = 'hidden'; btn.textContent = 'Show div'; } });
Even though the div
element is not rendered, it still affects the layout on
the page as normal.
When we used the display
property to hide the div
element, the button would
take its place in the DOM as the div
element got completely removed from the
document.