Search code examples
jqueryselectorcoalesce

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?


Solution

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