15
$.fn.sortByDepth = function() {
    var ar = [];
    var result = $([]);

    $(this).each(function() {
        ar.push({length: $(this).parents().length, elmt: $(this)});
    });
    ar.sort(function(a,b) {
        return b.length - a.length;
    });
    for (var i=0; i<ar.length; i++) {
        result.add(ar[i].elmt);
    };
    alert(result.length);
    return result;
};

In this function I try to create a jQuery collection from separate jQuery object. How can i do that ?

The code below doesn't work:

result.add(ar[i].elmt);

The jsfiddle: http://jsfiddle.net/hze3M/14/

2 Answers 2

18

.add() returns a new jQuery object. Change this line:

result.add(ar[i].elmt);

to this:

result = result.add(ar[i].elmt);

This still won't work, though

As of jQuery 1.4 the results from .add() will always be returned in document order (rather than a simple concatenation).

So you just use a vanilla JS array, push() the sorted elements into it, and then $() the whole thing.


Other code cleanup:

$.fn.sortByDepth = function() {
    var ar = this.map(function() {
            return {length: $(this).parents().length, elt: this}
        }).get(),
        result = [],
        i = ar.length;


    ar.sort(function(a, b) {
        return a.length - b.length;
    });

    while (i--) {
        result.push(ar[i].elt);
    }
    return $(result);
};


var x = $('input').sortByDepth().map(function() {
    return this.id;
}).get().join(' - ');

$('#selection').text(x);

http://jsfiddle.net/mattball/AqUQH/.

Sign up to request clarification or add additional context in comments.

4 Comments

thanks for your code cleanup i apreciate. Rocket was faster for the answer that's why i accept that one.
@alexl: yes, he was faster, but the code still won't work (see my latest edit).
arg, so all the code it's pointless if the add method reorder all the objects ...
nevermind didn't seen the last update. I didn't known you can create a jquery collection directly from the array good to see that.
4

.add returns a new object, and does not modify the old one.

Try changing:

result.add(ar[i].elmt);

To:

result = result.add(ar[i].elmt);

Also, $([]) is unneeded, you can just do var result = $();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.