I would like to select multiple buttons and click the first in order. Something like COALESCE
function.
I tried this:
$(".selector1, .selector2, .selector3").first().click();
This works but the selection follows the DOM order and not my selector query order. Any suggestion?
jQuery always returns elements in DOM order, so you'll need to do something along these lines:
$.each(['.selector1', '.selector2', '.selector3'], function(i, selector) {
var res = $(selector);
if (res.length) {
res.first().click();
return false;
}
});
You could poor that into a jQuery extension like so:
$.coalesce = function(selectors) {
var match;
var selector = $.each(selectors, function(i, selector) {
var res = $(selector);
if (res.length) {
match = res;
return false;
}
});
return match || $([]);
};
And then call
$.coalesce(['.selector1', '.selector2', '.selector3']).first().click();
Iterating over the elements with each() will give the right order, like so:
var elms = [".selector1", ".selector2", ".selector3"];
$.each(elms, function(index, item) {
$(item).append('<br><br>This is item '+index);
});
FIDDLE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With