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";
}
}