How to Hide & Show DOM Elements With Plain JavaScript

Learn how to hide and show DOM elements with plain, vanilla JavaScript.

JavaScript has a style property, fittingly called style, that can be used to set CSS properties on elements, and style them just like you can with CSS. Let’s try it!

This is how you hide a DOM element with JavaScript:

element.style.display = "none"

To display the DOM element again:

element.style.display = "block"

Note: if your DOM element was originally set to inline or inline-block, just replace the block value above with one of those values.

Practical example

In the example above, element is just a generic placeholder. To use JavaScript’s style property in a practical sense, you first need to select the DOM element you want to style.

Let’s say you have a button you want to remove from the DOM, called cta-button. You would do that like this:

const ctaButton = document.querySelector(".cta-button")

ctaButton.style.display = "none"

Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on