Categories
JavaScript Answers

How to Hide or Show Elements with JavaScript?

Spread the love

In many situations, we may want to create components that we can show and hide by toggling them.

In this article, we’ll look at how to hide or show elements with JavaScript.

Hide or Show Elements with JavaScript

We can show or hide elements with JavaScript by setting the style.display property of an element.

We can hide it by setting it to 'none' .

And we can show it by setting it to 'block' .

For instance, we can write the following HTML:

<button>
  toggle
</button>
<p>
  hello world
</p>

Then we can add the following JavaScript code:

const button = document.querySelector('button')
const p = document.querySelector('p')

button.addEventListener('click', () => {
  if (p.style.display === 'none') {
    p.style.display = 'block'
  } else {
    p.style.display = 'none'
  }
})

We add a button and p element with the HTML.

Then we select the elements with document.querySelector .

And then we add a click event listener with the button.addEventListener method.

We check if p.style.display is 'none' .

If it’s 'none' , then we set p.style.display to 'block' .

Otherwise, we set it to 'none' .

'none' makes the element disappear. No space is allocated for the element.

And 'block' makes it display as a block element.

Now when we click on the button, we see the p element being toggled on and off.

Alternatively, we can set the visibility property instead.

The difference between visibility and display is that visibility allocates space for the element no matter if it’s displayed or not.

This isn’t the case with display .

So we can also write:

const button = document.querySelector('button')
const p = document.querySelector('p')

button.addEventListener('click', () => {
  if (p.style.visibility === 'hidden') {
    p.style.visibility = 'visible'
  } else {
    p.style.visibility = 'hidden'
  }
})

And we get the same result in our example.

Conclusion

We can set the display property to 'block' or visibility to 'visible' to show an element.

And we can set the display property to 'none' or visibility to 'hidden' to hide an element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

2 replies on “How to Hide or Show Elements with JavaScript?”

I tried this on my own website, and found that the first time I click on my link, nothing happens. It only toggles after the next click.
It looks like the first time it queries the display value, it’s null.
Any ideas how to fix this?
Take a look at my CodePen page at https://codepen.io/bryanhiggs/pen/xxpyzXV to see how things are working for me. Click on the ‘DIRECTIONS’ link to see how it reacts. The first click doesn’t do anything. The second and subsequent ones toggle the way they should.
What am I missing?

Leave a Reply

Your email address will not be published. Required fields are marked *