Hide an Element by id using JavaScript

avatar

Borislav Hadzhiev

Last updated: Dec 28, 2021

banner

Check out my new book

Hide an Element by id using JavaScript #

To hide an element by id, select the element using the getElementById() method and set the element's style.display property to none. Setting the element's display property to none removes the element from the DOM, as if the element never existed on the page.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box">Box</div> <button id="btn">Hide Box</button> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const btn = document.getElementById('btn'); btn.addEventListener('click', () => { const box = document.getElementById('box'); // 👇️ removes element from DOM box.style.display = 'none'; // 👇️ hides element (still takes up space on page) // box.style.visibility = 'hidden'; });

We added an event listener to a button element that hides a div on click.

We used the document.getElementById method to get the element with id of box.

Note that we used the display css property in the example, however you might need the visibility property depending on your use case.

When an element's 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.

If you click on the button element from the example, the div element is removed from the DOM and the button element takes its place.

Here is an example that uses the visibility property to hide an element by its id.

index.js
const btn = document.getElementById('btn'); btn.addEventListener('click', () => { const box = document.getElementById('box'); // 👇️ hides element (still takes up space on page) box.style.visibility = 'hidden'; });

When the button is clicked, the div becomes invisible, however it still takes up space on the page.

On the other hand, if the element's display property is set to none, it no longer takes space on the page and often other elements shift and take its place.

Use the search field on my Home Page to filter through my more than 3,000 articles.