Last active
April 5, 2018 14:30
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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')); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment