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
  • 313,535
  • 40
  • 245
  • 254
JoeBe
  • 1,064
  • 1
  • 8
  • 22

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
  • 313,535
  • 40
  • 245
  • 254
2

Try this:

let hasClass = true;
$(".classA").each(function(){
  hasClass = hasClass && $(this).hasClass("classB")
})
Anurag Srivastava
  • 13,226
  • 4
  • 25
  • 40
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
  • 25,262
  • 9
  • 45
  • 70
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
  • 5,616
  • 1
  • 18
  • 49