Saravana
Saravana

Reputation: 40554

How to check if any of the elements satisfy a condition?

Is there any way to check if any of the elements in my selector satisfies a specific condition?

Currently I use:

var isSatisfied = false;
$("#myUL li").each(function() {
    if($(this).data("myconditon") === true) {
        isSatisfied = true;
    }
});
// Use isSatisfied here

This seems overly complex to do a simple job. What I'm looking for is something like Enumerable.Any in C#.

Upvotes: 1

Views: 930

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

You can use .is(), still you will have to do the condition check

var isSatisfied = $("#myUL li").is(function () {
    return $(this).data("myconditon") === true;
});

Upvotes: 1

Mitya
Mitya

Reputation: 34556

var isSatisfied = !!$("#myUL li").filter(function() {
    return $(this).data("myconditon") === true;
}).length;

.filter(), as its name suggests, retains only those items for which the callback returns true. So we end up with a jQuery stack. By querying its length, and coercing that to a boolean, you end up with your desired boolean var isSatisfied.

Upvotes: 1

Related Questions