1

I want to check if all objects of classA share also classB. However, with the following code, it throws true if at least one object has the classB:

$(".classA").hasClass("classB")

How can I check if all elements with classA also have classB? (with either jQuery or plain Javascript)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
JoeBe
  • 1,224
  • 3
  • 13
  • 28

4 Answers4

4

I'd use an array, and use Array.prototype.every:

const everyAHasB = [...document.querySelectorAll('.classA')]
  .every(a => a.classList.contains('classB'));

There's no need to require a big library like jQuery for something this simple.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
2

Try this:

let hasClass = true;
$(".classA").each(function(){
  hasClass = hasClass && $(this).hasClass("classB")
})
Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43
1

You could do something like:

var c = $(".classA").filter(function() {
  return !$(this).hasClass("ClassB");
})

This will return those elements that don't have ClassB

If you want to get all the Elements that has both classes, just remove the ! from !$(this)

Demo

var c = $(".classA").filter(function() {
  return !$(this).hasClass("ClassB");
})

console.log(c)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="classA ClassB"></div>
<div class="classA ClassB"></div>
<div class="classA ClassB"></div>
<div class="classA"></div>
<div class="classA ClassB"></div>
Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77
0

Just iterate over all elements and check for each of them:

let all=true;
$(".classA").each((el) => {
    if(!el.hasClass("classB")) all=false;
})

console.log(all)
MauriceNino
  • 6,214
  • 1
  • 23
  • 60