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?

This entry was posted in Programming and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>