Hide and Show an Element with JavaScript

Web Design & Web Development

In this article, I will introduce how to hide and show an element with JavaScript.

Style Display Property

To hide and show an element, you can use the JavaScript style display property.
This property sets or returns the element's display type.

When this property is set to none, it will hides the whole element.

Example

const element = document.getElementById('idName');
element.style.display = 'none';
Sponsored links

Demo

Click the "Hide / Show" button to toggle the display of the element.

Sponsored links

Code

HTML

<div id="el">Element</div>
<button type="button" id="btn">Hide/Show</button>

JavaScript

const element = document.getElementById('el');
const btn = document.getElementById('btn');

btn.addEventListener('click', () => {
  if (element.style.display !== 'none') {
    // Hide the element
    element.style.display = 'none';
  } else {
    // Show the element
    element.style.display = 'block';
  }
});