Skip to content

Instantly share code, notes, and snippets.

@jawdatls
Created May 11, 2015 08:29
Show Gist options
  • Save jawdatls/c08190fb55f8eb5ce71a to your computer and use it in GitHub Desktop.
Save jawdatls/c08190fb55f8eb5ce71a to your computer and use it in GitHub Desktop.
Sort DOM Elements with jQuery
<ul class="js-people">
<li data-name="John Doe">Mr. John Doe</li>
<li data-name="Trent Richardson">Mr. Trent Richardson</li>
<li data-name="Cindy Smith">Ms. Cindy Smith</li>
<li data-name="Bill Williams">Mr. Bill Williams</li>
<li data-name="Jane Doe">Mrs. Jane Doe</li>
</ul>
<script>
$(document).ready(function(){
var $people = $('ul.js-people'),
$peopleli = $people.children('li');
$peopleli.sort(function(a,b){
var an = a.getAttribute('data-name'),
bn = b.getAttribute('data-name');
if(an > bn) {
return 1;
}
if(an < bn) {
return -1;
}
return 0;
});
$peopleli.detach().appendTo($people);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment