How To Check If All Objects Of Specific Class Share Another Class As Well?
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')
Solution 1:
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.
Solution 2:
Try this:
let hasClass = true;
$(".classA").each(function(){
hasClass = hasClass && $(this).hasClass("classB")
})
Solution 3:
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)
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><divclass="classA ClassB"></div><divclass="classA ClassB"></div><divclass="classA ClassB"></div><divclass="classA"></div><divclass="classA ClassB"></div>
Solution 4:
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)
Post a Comment for "How To Check If All Objects Of Specific Class Share Another Class As Well?"