skip to Main Content

I have found this code for a hide/show ID effect. I am building with Elementor in WP.

<button onclick="myFunction()">show / hide</button>
function myFunction() {
  var x = document.getElementById ("showprice");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
} 

This works, but I would like to modify the code to hide/show a Class instead of ID – but changing it to the following doesn’t work. Any tips?

function myFunction() {
  var x = document.getElementsByClassName("showprice");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
} 

3

Answers


  1. getElementsByClassName returns a HTMLCollection. So it returns an array 🙂
    You should probably do a loop to iterate over all the elements and then apply your logic:

    function myFunction() {
      var elts = document.getElementsByClassName("showprice");
      elts.map((x) => {
         if (x.style.display === "none") {
           x.style.display = "block";
         } else {
           x.style.display = "none";
         }
      })
    } 
    
    Login or Signup to reply.
  2. Using getElementsByClassName returns a collection of elements rather than a single element like getElementById.
    So you need to loop through each element in the collection to apply the style changes

    <button onclick="myFunction()">show / hide</button>
    
    <script>
    function myFunction() {
      var x = document.getElementsByClassName("showprice");
      for (var i = 0; i < x.length; i++) {
        if (x[i].style.display === "none" || x[i].style.display === "") {
          x[i].style.display = "block";
        } else {
          x[i].style.display = "none";
        }
      }
    }
    </script>
    
    • Looping through all elements with class name ‘showprice’.
    • We’re checking its current display style and toggling it accordingly.
    • If the elements style is ‘none’ or empty, we set it to ‘block’ to show it, else ‘none’ to hide it.

    This should achieve the hide/show effect for elements with the class "showprice".

    Login or Signup to reply.
  3. You can also use querySelector or querySelectorAll to select a class or multiple class with same name and then loop through it with the forEach method as below:

    function myFunction() {
        var x = document.querySelectorAll(".showprice");
        x.forEach(elem=>{
            if (elem.style.display === "none") {
                elem.style.display = "block";
              } else {
                elem.style.display = "none";
              }
        })
      } 
    <button onclick="myFunction()">show/hide</button>
    <div class="showprice">hello</div>
    <div class="showprice">hello</div>
    <div class="showprice">hello</div>
    <div class="showprice">hello</div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search