Sach
Sach

Reputation: 75

jQuery .is( selector ) - where ALL selectors match the argument?

if ($('.A, .B, .C').is(':visible'))

-returns true if at least one of these elements matches the given argument.

How do I change it so that it returns true ONLY if ALL of these elements matches the given argument? (The argument could be changed to :hidden for this example but that is not what I am looking for)

Upvotes: 1

Views: 29

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075915

One handy way is Array.prototype.every:

if ($('.A, .B, .C').get().every(function(e) { return $(e).is(":visible"); })) {

...which looks less unwieldy using ES2015 (aka "ES6") arrow function syntax:

if ($('.A, .B, .C').get().every(e => $(e).is(":visible"))) {

every returns true if the callback returns a truthy value for all of the elements, false if the callback returns a falsy value, and stops as soon as it sees it's going to be false.

Another handy way is filter:

var elements = $('.A, .B, .C');
if (elements.filter(":visible").length === elements.length) {
    // Yes, they're all visible
}

You could give yourself a handy areAll function:

$.fn.areAll = function(arg) {
    return this.get().every(function(e) { // Or of course use
        return $(e).is(arg);              // the `filter` version
    });                                   // here if you prefer
};

...and then

if ($('.A, .B, .C').areAll(":visible")) {
    // ...
}

Upvotes: 2

Related Questions