Maria Popovici
Maria Popovici

Reputation: 49

Javascript get all elements with one class of two

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

Answers (4)

santosh
santosh

Reputation: 575

if you use jquery

$("div.cat-box")

Upvotes: -1

Ankit Agarwal
Ankit Agarwal

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

Reinstate Monica Cellio
Reinstate Monica Cellio

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

Volodymyr
Volodymyr

Reputation: 1408

You can use :not CSS pseudo-class to achieve this: document.querySelectorAll('.cat-box:not(.hidden)');

Upvotes: 3

Related Questions