Why does my JS function only manipulate one <div> that is assigned to the class instead of all?
Solution 1:
I copied your code into the context of a very simple page (see below) and it seems to work...I might have missed something, but could the issue be elsewhere in your project? Perhaps investigating it piece by piece in the browser console could help.
<!DOCTYPE html>
<html>
<script>
function myFunction(){
var elms = document.getElementsByClassName("tw");
Array.from(elms).forEach((x) => {
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
})
}
</script>
<body>
<button onclick="myFunction()">Click me</button>
<div class="tw">1</div>
<div class="tw" style="display: block;">2</div>
<div class="tw">3</div>
<div class="tw" style="display: block;">4</div>
</body>
</html>