Buttons to hide and show an element in JavaScript

In this section, we will learn how to hide and show page elements. As usual, we will start with something simple, and we will gradually complicate.

Suppose we have a paragraph and two buttons to warm up:

<p id="elem">text</p> <input type="submit" id="show" value="show"> <input type="submit" id="hide" value="hide">

Let's get references to our elements into variables:

let elem = document.querySelector('#elem'); let show = document.querySelector('#show'); let hide = document.querySelector('#hide');

Now let's make it so that by clicking on one button our paragraph is hidden, and on the other it is shown. To do this, we will add or remove the corresponding CSS class to the element:

.hidden { display: none; }

Let's solve our problem:

hide.addEventListener('click', function() { elem.classList.add('hidden'); }); show.addEventListener('click', function() { elem.classList.remove('hidden'); });

Modify my code so that there is only one button. Let the element be shown on the first click on this button, and hidden on the second.

enru