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
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:
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
This should achieve the hide/show effect for elements with the class "showprice".
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: