In an article, I wrote how to hide and show DOM elements using inline styles in JavaScript. Today, you'll learn to hide and show elements using CSS classes in JavaScript.

Let us first declare a simple CSS class that hides the element, if applied, by setting display: none:

.hidden {
    display: none;

Next, say we have the following <button> element:

<button class="btn">Click Me</button>

Now, if you want to hide the above button from the DOM, add the hidden class by using the add() method provided by the classList object, like below:

// grab button element
const button = document.querySelector('.btn')

// hide it

To show the element again, simply removes the hidden class using the classList.remove() method:


While inline styles work perfectly to toggle the element visibility, the CSS class gives you more flexibility to control the behavior like this.

Creating hide() & Show() methods

The classList object provides methods to add, remove, and toggle CSS classes from an element in JavaScript.

Let us use classList to create our own jQuery-like hide(), show(), and toggle() methods in pure JavaScript:

// hide an element
const hide = elem => {

// show an element
const show = elem => {

// toggle the element visibility
const toggle = elem => {

Now, if you want to hide or show any DOM element, call the above method:

// hide

// show

// toggle

Read this guide to learn more about handling CSS classes in vanilla JavaScript.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.