Created
May 11, 2015 08:29
-
-
Save jawdatls/c08190fb55f8eb5ce71a to your computer and use it in GitHub Desktop.
Sort DOM Elements with jQuery
This file contains 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
<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