Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery multiple selectors order

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?

like image 513
Tobia Avatar asked Feb 20 '23 18:02

Tobia


2 Answers

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();

like image 200
Gerry Avatar answered Mar 02 '23 17:03

Gerry


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

like image 20
adeneo Avatar answered Mar 02 '23 17:03

adeneo