Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve order of items added to jQuery matched set?

I am trying to add elements to a jQuery object in a specific order. However, the result set is ordered the same as the DOM tree. For example:

<div>one</div>
<span>two</span>
<p>three</p>

...

var $result = $("span").add("p").add("div");

I want a result set where $result[0] is the span, $result[1] is the p, and so on. However, they are ordered the same as in the DOM.

Is there another way to build out a jQuery object like I'm intending, other than .add()?

I'm aware that I could assign some data property to them to specify order, and sort my result set by that. However, this will need to happen dozens of times within my app and having to assign order data values and sorting each time will be really ugly, and would take too long to implement.

like image 548
Danny Avatar asked Nov 08 '12 03:11

Danny


1 Answers

You can use the native Array.push:

$.fn.push = function(selector) {
    Array.prototype.push.apply(this, $.makeArray($(selector)));
    return this;
};

var $result = $("span").push("p").push("div");

DEMO: http://jsfiddle.net/ZUAcy/

You might think that jQuery does this behind the hood of add() but it actually return a pushStack from the function to optimize it’s selectors: http://james.padolsey.com/jquery/#v=1.7.2&fn=jQuery.fn.add

like image 140
David Hellsing Avatar answered Oct 30 '22 15:10

David Hellsing