Wednesday, March 25, 2009

Using jQuery Manipulation Functions (Append, Prepend, After, Before) To Reorder Items

I discovered something interesting quite by accident today. I was trying to figure out the best way to reorder certain <li> items based on the value of a particular trait (while ignoring those <li> items that didn't have that particular trait at all). I figured the best way to accomplish this was to:

  1. Select all of the items that had the trait and store them in an array
  2. Resort the contents of the array into a new array.
  3. Delete the selected items from the list (so as not to replicate them)
  4. Loop through the new array and add the items back into the list using the jQuery prepend() function to put them at the top of the list.

When I ran my first test of my code, I left out the deletion step so I could compare the original item order with the new item order, figuring I would have duplicates of the selected items.

However, I was surprised to discover that prepend() removed the original instances of the selected list items, leaving only the prepended copies. Essentially, it ended up moving the items rather than duplicating them.

There's nothing on the official documentation page that says that if you're prepending an item to a collection that already contains an instance of that item that it will remove the original item for you, but that's apparently what it's programmed to do.

I ran a quick test of some of the other related Manipulation functions (append(),after(),before()), and they all seem to behave that way as well.

Thought it was worth sharing. Certainly makes my reordering task a bit easier.

No comments:

Post a Comment