Pretty simple to do with loop but I'm wondering if there's a way to see if every item in a collection matches a condition without a loop. For example:
if( $('.many-items-of-this-class').hasClass('some-other-class') ) { }
This returns true if any item in the collection returns true. Is there a way to do this sort of operation so it only returns true if all items are true?
You could cache the set, then run a filter against the set that tests for the other class, and compare the .length
properties of both.
var many_items = $('.many-items-of-this-class');
if( many_items.length === many_items.filter('.some-other-class').length ) { }
Or shorter, but arguably more confusing, you could use a .not()
filter with .length
and a !
.
var many_items = $('.many-items-of-this-class');
if( !many_items.not('.some-other-class').length ) { }
You could easily write a plugin to extend the each functionality.
(function( $ ){
$.fn.allMustPassTest = function(test,params) {
var allPass = true;
$(this).each(function(){
if(!test.apply($(this),params)){
allPass = false;
}
});
return allPass;
};
})( jQuery );
And use as such:
var allPass = $('.many-items-of-this-class').allMustPassTest(function(){
return $(this).hasClass('some-other-class');
});
if(allPass){
//code to execute if all items have .some-other-class
}
Or another way:
var hasClassTest = function(clazz){
return $(this).hasClass(clazz);
};
if($('.many-items-of-this-class').allMustPassTest(hasClassTest,['some-other-class'])){
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With