jQuery list insertion sort plugin
Here’s a basic jQuery sorting plugin for generic parent child relationships I wrote.
Wherein ‘element’ is the html you wish to insert and ‘value’ is what the associated weight of the element I’m inserting. For now it compares the weight value to the DOM text within the other children.
$.fn.insertSort = function(element, value) {
selector = this;
if ($(selector).length > 0) {
$(selector).attr("inserted", "false");
$(selector).children().each(function() {
if (parseInt($(this).text()) > parseInt(value)) {
$(this).before(element);
$(selector).attr("inserted", "true");
return false;
}
});
if ($(selector).attr("inserted") == "false") {
$(selector).append(element);
}
} else {
$(selector).append(element);
}
$(selector).removeAttr("inserted");
};
It should be noted that this is an insertion sort. It’d be good to extend the plugin to be able to sort an existing piece of html for any parent/child relationship. Possibly with the ability to specify a particular level of depth?
Tags: jQuery, Programming