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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With