Sort jQuery elements
Trying to figure out a more scalable solution to sorting DOM elements using jQuery
by juErik
HTML
<div id="original">
<div timestamp="99">99</div>
<div timestamp="999">999</div>
<div timestamp="12">12</div>
<div timestamp="11">11</div>
<div timestamp="10">10</div>
<div timestamp="99">9</div>
<div timestamp="8">8</div>
<div timestamp="7">7</div>
<div timestamp="6">6</div>
<div timestamp="5">5</div>
<div timestamp="4">4</div>
<div timestamp="3">3</div>
<div timestamp="2">2</div>
<div timestamp="1">1</div>
<div timestamp="9999">9999</div>
</div>
<h1>Results</h1>
<div id="results"></div>
<h1>jQuery calls <span id="calls"><span/></h1>
CSS
body {
background-color: #1c2128;
color: #fff;
margin: 20px;
}
JavaScript
// get array of elements
var myArray = $("#original div");
var count = 0;
// sort based on timestamp attribute
myArray.sort(function (a, b) {
// convert to integers from strings
a = parseInt($(a).attr("timestamp"), 10);
b = parseInt($(b).attr("timestamp"), 10);
count += 2;
// compare
if(a > b) {
return 1;
} else if(a < b) {
return -1;
} else {
return 0;
}
});
// put sorted results back on page
$("#results").append(myArray);
$("#calls").append(count+1);