# Hide and show DOM elements using a CSS class in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Mar 5, 2020, updated Oct 15, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-hide-show-elements-using-css-class

> A quick article to learn how to hide and show different DOM elements using CSS classes in vanilla JavaScript.

In [an article](https://attacomsian.com/blog/javascript-hide-show-dom-elements), I wrote how to hide and show DOM elements using [inline styles](https://attacomsian.com/blog/javascript-dom-style-property) 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`:

```css
.hidden {
    display: none;
}
```

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

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

Now, if you want to **hide** the above button from the [DOM](https://attacomsian.com/blog/getting-dom-elements-javascript), add the `hidden` class by using the `add()` method provided by the [classList](https://attacomsian.com/blog/javascript-add-remove-toggle-css-classes#using-classlist-property) object, like below:

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

// hide it
button.classList.add('hidden')
```

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

```javascript
button.classList.remove('hidden')
```

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:

```javascript
// hide an element
const hide = elem => {
  elem.classList.add('hidden')
}

// show an element
const show = elem => {
  elem.classList.remove('hidden')
}

// toggle the element visibility
const toggle = elem => {
  elem.classList.toggle('hidden')
}
```

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

```javascript
// hide
hide(document.querySelector('.btn'))

// show
show(document.querySelector('.btn'))

// toggle
toggle(document.querySelector('.btn'))
```

Read [this guide](https://attacomsian.com/blog/javascript-add-remove-toggle-css-classes) to learn more about handling CSS classes in vanilla JavaScript.
