How to show and hide the text in Vanilla JS?

Viewed 1064

I want to show and hide the text in Vanilla JS and unfortunately, all I can do is to hide the text. I don't know how to show the text again.

<button id="button">my button</button>
<div> 
 <p id="text">Hello</p>
</div>

this is the js

const z = document.getElementById('text');
const y = document.getElementById('button');

y.onclick = () => {
    z.style.display = 'none';
};
2 Answers

Using a class is usually easier, because you can simply toggle it:

const z = document.getElementById('text');
const y = document.getElementById('button');

y.addEventListener('click', () => {
    z.classList.toggle('hidden');
});
.hidden { display: none; }
<button id="button">my button</button>
<div> <p id="text">Hello</p> </div>

This is also a toggle with which you can refer to the element's style.

const z = document.getElementById('text');
const y = document.getElementById('button');

y.onclick = function() {
  z.style.display = z.style.display === 'none' ? '' : 'none';
}
<button id="button">my button</button>
<div> 
  <p id="text">Hello</p>
</div>

Related