Search code examples
javascripthtmlshow-hide

Show/hide text using getElementsByClassName for all classes


I am trying to show/hide text with the same class. I tried the following code that hides only the first id getElementById, which makes me decide to remove all IDs and just keep the class.

The text/words to be hidden are in different positions in the page (so I can't just add a whole div around it, as I want to keep other text visible all the time).

I want to use getElementsByClassName instead, but I can't seem to get it working.

function showhide() {
   var div = document.getElementById("newpost");
   div.classList.toggle('hidden'); 
}
.hidden{
    display : none;
}
<button id="button" onclick="showhide()">Click Me</button>
<span id="newpost" class="hidden"><p>text 1</p></span>
<span id="newpost" class="hidden">text 2</span>
<span id="newpost" class="hidden"><p>text 3</p></span>


Solution

  • You need two classes:

    • one to designate the elements that you want to toggle (hidable in the example below)
    • one to control whether an element is currently hidden (hidden in the example).

    function showhide() {
      for (var elem of document.getElementsByClassName("hidable"))
        elem.classList.toggle("hidden");
    }
    .hidden {
      display: none;
    }
    <button onclick="showhide()">Click Me</button>
    <span class="hidable hidden"><p>text 1</p></span>
    <span class="hidable">text 2</span>
    <span class="hidable hidden"><p>text 3</p></span>