Reputation: 49
i have many divs with class="cat-box" and class="cat-box hidden".
I create a javascript to view all classes with cat-box, but it's counting both of "cat-box" and "cat-box hidden".
How can I count only elements with class cat-box?
My script:
function GetMore() {
var allvis = document.getElementsByClassName('cat-box').length;
alert(allvis);
}
Upvotes: 1
Views: 85
Reputation: 30739
Use querySelector
and not
in your javascript for that:
function GetMore() {
var allvis = document.querySelectorAll('.cat-box:not(.hidden)').length;
alert(allvis);
}
function GetMore() {
var allvis = document.querySelectorAll('.cat-box:not(.hidden)').length;
alert(allvis);
}
GetMore();
<div class="cat-box"></div>
<div class="cat-box"></div>
<div class="cat-box hidden"></div>
Upvotes: 0
Reputation: 26143
Use document.querySelectorAll()
with a selector that excludes the hidden
elements.
Here's an example...
function GetMore() {
var allvis = document.querySelectorAll('.cat-box:not(.hidden)').length;
alert(allvis);
}
document.getElementById("count").addEventListener("click", GetMore);
.hidden { color: rgb(200, 200, 200); }
<div class="cat-box">cat box</div>
<div class="cat-box hidden">cat box</div>
<div class="cat-box">cat box</div>
<div class="cat-box hidden">cat box</div>
<div class="cat-box">cat box</div>
<button id="count">count</button>
Upvotes: 2
Reputation: 1408
You can use :not
CSS pseudo-class to achieve this:
document.querySelectorAll('.cat-box:not(.hidden)');
Upvotes: 3