JQuery sort order

I would like to select a few buttons and click in order. Something like a function COALESCE.

I tried this:

$(".selector1, .selector2, .selector3").first().click();

This works, but the choice follows the DOM order, not my order of choice queries. Any suggestion?

+3
source share
3 answers

jQuery always returns elements in DOM order, so you need to do something on these lines:

$.each(['.selector1', '.selector2', '.selector3'], function(i, selector) {
    var res = $(selector);
    if (res.length) {
        res.first().click();
        return false;
    }
});

You could use this in a jQuery extension, for example:

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

+5
source

Iterating over the elements with each () will give the correct order, for example:

var elms = [".selector1", ".selector2", ".selector3"];

$.each(elms, function(index, item) {
    $(item).append('<br><br>This is item '+index);
});​

Fiddle

+2
source

get() , , :

$($(".selector1").get().concat($(".selector2").get(), $(".selector3").get())).first().click();
0

All Articles