0

I am trying to create a function as part of a WordPress site, to show/hide page elements with a certain class. E.g. any page elements (rows, containers, text-blocks etc.) that use the class 'show-hide', should be hidden/shown with the click of a button.

I have got it working, but I'm sure there must be a better method to achieve a similar result. I'd like to be able to select ALL the show-hide classes on the page without specifying a number ( [1], [2], [3], [3], [6]... ) for each time it's used.

I'm really new to javascript, so any help or advice, on generating a range of values or using wildcard * symbols to achieve this would be appreciated.

function myFunction() {
  var x = document.getElementsByClassName("show-hide");

  if (x[0].style.display === "none") {
    x[0].style.display = "block";
  } else {
    x[0].style.display = "none";
  }
  if (x[1].style.display === "none") {
    x[1].style.display = "block";
  } else {
    x[1].style.display = "none";
  }
  if (x[2].style.display === "none") {
    x[2].style.display = "block";
  } else {
    x[2].style.display = "none";
  }
  if (x[3].style.display === "none") {
    x[3].style.display = "block";
  } else {
    x[3].style.display = "none";
  }
}
Jordan Running
  • 102,619
  • 17
  • 182
  • 182
Steve
  • 1

3 Answers3

1

As answered above you can use a loop. Here's a shorthand:

for(let elem of Array.from(document.getElementsByClassName("show-hide"))) {
   elem.style.display = (elem.style.display === 'block') ? 'none' : 'block';
}
schapke
  • 338
  • 2
  • 6
0

As noted int the comments, you're looking for looping:

function myFunction() {
  var x = document.getElementsByClassName("show-hide");

  [...x].forEach(xx => {
    if (xx.style.display === "none") {
      xx.style.display = "block";
    } else {
      xx.style.display = "none";
    }
  });
}

Note the [...x] spread operator which will convert an itterable (HTMLCollection in this case) to an array.

junvar
  • 11,151
  • 2
  • 30
  • 46
  • Thank you, this one has worked for me and also made the most sense with my very limited knowledge of javascript. – Steve Apr 25 '19 at 12:01
0

You can make an array from your HTML Collection and simply use map :

function myFunction() {

  Array.from(document.getElementsByClassName("show-hide")).map(function(elem){
    if (elem.style.display === "none") { 
      elem.style.display = "block" 
    } else {
      elem.style.display = "none";
    }
  })

};
Andu Andrici
  • 853
  • 1
  • 5
  • 12