Skip to content

Instantly share code, notes, and snippets.

@amelieykw
Last active April 5, 2018 14:30
Show Gist options
  • Save amelieykw/3e839c9d49d1fa3f903b634d992e4e4b to your computer and use it in GitHub Desktop.
Save amelieykw/3e839c9d49d1fa3f903b634d992e4e4b to your computer and use it in GitHub Desktop.
[jQuery sort divs - by DOM element attribut] #jQuery #javascript #sort_divs #html #css
<div id="sortexample">
<div class="sortitem" sortweight="5">Pears [sortweight: 5]</div>
<div class="sortitem" sortweight="3">Apples [sortweight: 3]</div>
<div class="sortitem" sortweight="1">Cherries [sortweight: 1]</div>
<div class="sortitem" sortweight="4">Oranges [sortweight: 4]</div>
<div class="sortitem" sortweight="2">Strawberries [sortweight: 2]</div>
</div>
// sort by attributes - usage for our example: sort_div_attribute('sortweight');
function sort_div_attribute(attname) {
// copy all divs into array and destroy them in the page
divsbucket = new Array();
divslist = $$('div.sortitem');
for (a=0;a<divslist.length;a++) {
divsbucket[a] = new Array();
// we'vev passed in the name of the attribute to sort by
divsbucket[a][0] = divslist[a].get(attname);
divsbucket[a][1] = divslist[a].dispose();
}
// sort array by sort attribute content
divsbucket.sort(function(a, b) {
if (a[0].toLowerCase() === b[0].toLowerCase()) {
return 0;
}
if (a[0].toLowerCase() > b[0].toLowerCase()) {
return 1;
} else {
return -1;
}
});
// re-inject sorted divs into page
for (a=0;a<divslist.length;a++) {
divsbucket[a][1].inject($('sortexample'));
}
}

Figure - sort divs by HTML content

Figure - sort divs by the value of the attribute

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment