Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery test a condition vs entire collection without a loop

Tags:

jquery

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?

like image 224
Will Avatar asked Jun 09 '11 17:06

Will


2 Answers

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 ) { }
like image 172
user113716 Avatar answered Nov 19 '22 21:11

user113716


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'])){

}
like image 1
joekarl Avatar answered Nov 19 '22 20:11

joekarl