Connell
Connell

Reputation: 14411

jquery is() to match all elements, not any

If I have this HTML:

<input type="button" />
<input type="button" />
<input class="btn" type="button" />
<div class="btn"></div>
<div class="btn"></div>

I have 3 buttons in a jQuery object.. say var buttons = $(':button');.

Then I have another object that has a different 3 set of elements, ONE of them, being the same: var nextButtons = $('.btn');

Is there a jQuery way of checking if all the elements are the same? is() seems to return true if any of the elements match.

EDIT:

I mean a comparison in the exact same way that is() works. I'd guess, this function would call is() for each element in the first set, for each of the second set.

Upvotes: 1

Views: 106

Answers (3)

user1565195
user1565195

Reputation: 877

if (buttons.length === nextButtons.length && buttons.filter(nextButtons).length) {
     console.log("Same");
}

Upvotes: 0

TheVillageIdiot
TheVillageIdiot

Reputation: 40507

You can try .filter()

var buttons= $(".btn").filter(function(i){
                   return $(this).is("input[type='button']");
              });

fiddle

Upvotes: 0

Jon
Jon

Reputation: 437424

There's nothing built-in, but it's really easy to do:

$.fn.all = function(selector) {
    return this.filter(selector).length == this.length;
}

See it in action.

Upvotes: 5

Related Questions