Reputation: 397
I need a vanilla JS way to count the number of hidden divs on a page.
I have three divs with inline styles display: none
. I thought this would work, but no luck:
var hiddenContainers = (document.getElementsByClassName(".emp-container").style.display == "none").length;
I have tried several solutions from SO and found a few JQuery ones that were successful, but what I'm writing needs to be done exclusively in regular old JavaScript.
EDIT: This works, but it seems like an unnecessarily roundabout way to get what I want:
var hiddenContainers = [];
var containers = document.querySelectorAll(".emp-container");
for (var i = 0; i < containers.length; i++) {
if (containers[i].style.display == "none") {
hiddenContainers.push(containers[i]);
}
}
Upvotes: 0
Views: 635
Reputation: 887
function countclick(){
var m = document.querySelectorAll('.divs[style*="display:none;"]').length;
document.getElementById('count').innerHTML = "Hidden Divs: "+m;
}
<div class='divs' style="display:none;">a</div>
<div class='divs' style="">b</div>
<div class='divs' style="">c</div>
<div class='divs' style="display:none;">d</div>
<div class='divs' style="">e</div>
<div class='divs' style="display:none;">f</div>
<hr/>
<span id="count">Hidden Divs: 0</span><br/>
<button onclick='countclick();'>Count</button>
Upvotes: 1