Jquery test condition against entire collection without loop

It's pretty simple to make a loop, but I'm wondering if there is a way to see if each item in the collection matches a condition without a loop. For instance:

if( $('.many-items-of-this-class').hasClass('some-other-class') ) { }

Returns true if any item in the collection returns true. Is there a way to perform such an operation that it returns true only if all the elements are correct?

+5
source share
6 answers

You can cache the set, and then run a filter against the set, which checks for another class, and compare the properties of .lengthboth.

var many_items = $('.many-items-of-this-class');

if( many_items.length === many_items.filter('.some-other-class').length ) { }

Or shorter, but perhaps more confusing, you can use a filter .not()with .lengthand !.

var many_items = $('.many-items-of-this-class');

if( !many_items.not('.some-other-class').length ) { }
+5
source

.

(function( $ ){
   $.fn.allMustPassTest = function(test,params) {
       var allPass = true;
       $(this).each(function(){
           if(!test.apply($(this),params)){
               allPass = false;
           }
       });
       return allPass;
   };
})( jQuery );

:

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

}

:

var hasClassTest = function(clazz){
    return $(this).hasClass(clazz);
};
if($('.many-items-of-this-class').allMustPassTest(hasClassTest,['some-other-class'])){

}
+1
var $many = $('.many-items-of-this-class');
if ( many.filter('.some-other-class').length == $many.length )
{
  // all items have the class.
}

Maybe? Other options are to create your own Selector . eg.

.many-items-of-this-class:and(.some-other-class)

or something like that.

0
source

What is the purpose of checking it? If you perform an operation, you can simply check both classes at the same time for the selector chains :

$('.many-items-of-this-class.some-other-class').each(
    function(index, value) {
        // Do stuff here
    });
0
source
if( ! $('.many-items-of-this-class').is(':not(.some-other-class)') ) { }

or, if the collection is based on a selector, simply

if( $('.many-items-of-this-class:not(some-other-class)').length == 0 ) { }
0
source
if( $('.many-items-of-this-class :not(.some-other-class)').size() == 0 ) { 
    // ...
}
0
source

All Articles