$.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/
each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.
When a jQuery object is passed to the $() function, a clone of the object is created. This new jQuery object references the same DOM elements as the initial one.
The Document Object Model (DOM for short) is a representation of an HTML document. It may contain any number of DOM elements. At a high level, a DOM element can be thought of as a "piece" of a web page. It may contain text and/or other DOM elements.
Answer: Use the jQuery append() or prepend() method You can add or insert elements to DOM using the jQuery append() or prepend() methods. The jQuery append() method insert content to end of matched elements, whereas the prepend() method insert content to the beginning of matched elements.
.add()
returns a new jQuery object. Change this line:
result.add(ar[i].elmt);
to this:
result = result.add(ar[i].elmt);
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/.
.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 = $();
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