I have created button that view the elements that is hidden onclick but there are many div with same id but it i want to hide all but its hidding only one i am using below code but its just viewing or hidding, the first div only hidding onclick rest its not hidding
<button onclick="myFunction()" class="btn-custom">View the Picture</button>
<div id=hide></div>
<div id=hide></div>
<div id=hide></div>
<div id=hide></div>
<script>
function myFunction() {
var x = document.getElementById("hide");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
Your HTML is invalid - ids must be unique.
Instead, use a class to identify the elements and querySelectorAll to select all of them:
<div class=hide>a</div>
<div class=hide>b</div>
<div class=hide>c</div>
<div class=hide>d</div>
<button onclick="myFunction()">Toggle</button>
<script>
function myFunction() {
var x = document.querySelectorAll(".hide");
x.forEach(y => {
if (y.style.display === "none") {
y.style.display = "block";
} else {
y.style.display = "none";
}
})
}
</script>