0
votes

I have a decent command of HTML and CSS but a complete newbie when it comes to Javascript.

I have a simple HTML page that I would like to include a button on, to toggle the display of text already wrapped in a span class e.g.

<span class="xxx">TEXT</span>

There are two separate span classes I'm using and ideally, I'd like the click of one button to show/hide both.

Right now I'm using CSS to hide them using the property "Display: none".

Can you show me how to achieve this? Hope this clear, thank you.

2
Once you have selected the elements you want to toggle, this can be done by either adjusting the classes in the classList property on them, or setting their inline styling with the style property. - Taplar

2 Answers

0
votes

This should work (ES6):

let btn = document.getElementById('btn');
let toggle = document.querySelectorAll('.toggle');

btn.onclick = () => { 
  for(let x of toggle) {
    x.classList.toggle('hide');
  }
};
.toggle.hide {
  display: none;
}
<button id="btn">Toggle</button>
<p>Name: <span class="toggle name">John</span></p>
<p>Age: <span class="toggle age">20</span></p>
0
votes

Using Vanilla Javascript on ES5 syntax:

function toggleSpanElements() {
 var span1 = document.querySelector('#span1');
 var span2 = document.querySelector('#span2');
 span1.style.display = span1.style.display === 'none' ? 'block' : 'none';
 span2.style.display = span2.style.display === 'none' ? 'block' : 'none';
}

Just attach that function to your button in the following way:

    <button onclick="toggleSpanElements()">Toggle!</button>