Skip to content

Instantly share code, notes, and snippets.

@johnivanoff
Last active July 27, 2017 03:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnivanoff/93c19e578c594d0d2fcb99195cdbd64f to your computer and use it in GitHub Desktop.
Save johnivanoff/93c19e578c594d0d2fcb99195cdbd64f to your computer and use it in GitHub Desktop.
Sort a HTML List Alphabetically by data-attribute
<!DOCTYPE html>
<html>
<title>Sort a HTML List Alphabetically HB</title>
<style>
div{
border: solid;
padding: 1em;
margin: 1em;
}
</style>
<body>
<th1>Sort a HTML List Alphabetically HB</h1>
<p>Click the button to sort the list alphabetically:</p>
<button onclick="sortList('acs')">Sort Project ASC</button>
<button onclick="sortList('desc')">Sort Project desc</button>
<section id="id01">
<div data-project="Powersites-v5">Powersites-v5 - ActionView::Template::Error</div>
<div data-project="VMS Rails">VMS Rails - TinyTds::Error</div>
<div data-project="Powersites-v5">Powersites-v5 - NoMethodError</div>
<div data-project="Acompany-Video">Acompany-Video - SignalException</div>
<div data-project="powersites-rails">powersites-rails - JSON::ParserError</div>
<div data-project="CL Payment Bot">CL Payment Bot - Redis::TimeoutError</div>
</section>
<script>
function sortList(order) {
var list, i, switching, b, shouldSwitch;
list = document.getElementById("id01");
switching = true;
/*Make a loop that will continue until
no switching has been done:*/
while (switching) {
//start by saying: no switching is done:
switching = false;
b = list.getElementsByTagName("DIV");
//Loop through all list-items:
for (i = 0; i < (b.length - 1); i++) {
//start by saying there should be no switching:
shouldSwitch = false;
/*check if the next item should
switch place with the current item:*/
if (order === 'acs') {
if (b[i].dataset.project.toLowerCase() > b[i + 1].dataset.project.toLowerCase()) {
/*if next item is alphabetically
lower than current item, mark as a switch
and break the loop:*/
shouldSwitch= true;
break;
}
} else {
if (b[i].dataset.project.toLowerCase() < b[i + 1].dataset.project.toLowerCase()) {
/*if next item is alphabetically
lower than current item, mark as a switch
and break the loop:*/
shouldSwitch= true;
break;
}
}
}
if (shouldSwitch) {
/*If a switch has been marked, make the switch
and mark the switch as done:*/
b[i].parentNode.insertBefore(b[i + 1], b[i]);
switching = true;
}
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment