Not sure why, but some programming tasks come in clusters - for several recent projects in a row I needed a way to sort divs in a page based on their content. Each of the projects had different enough frameworks that I had to re-implement div sorting several times in a row and I thought I create this page so that I have a basic version of this as a cheatsheet for future projects.
As a side note, many of the examples I've found online don't work in all browsers due to small differences in how array sort has been implemented by the browser manufacturers. I finally found clues as to why in the comments to this post on antipode.
My solution may not be the most elegant way of doing this and I'm specifically using MooTools as base framework, but I hope that this example will be useful for other programmers, too. Let me know in the comments below what you think.
You may also be interested in some of my other articles around HTML5, CSS3 and JavaScript.
Example
Here is a simple example of a group of divs that can be sorted either by their HTML content or by custom attribute values:
Sort alphabetically by HTML content
Sort low to high by the value of the attribute "sortweight"
Code
There are only a few requirements for this code to work: There has to be a container element that holds all the sortable divs and all the divs share a classname. Also, this example uses MooTools and its $ and $$ functions as well as Element.dispose() and Element.inject(), but this should be easy to change to jQuery or other frameworks.
HTML:
JavaScript: