
Untitled
By: a guest on
Jun 30th, 2012 | syntax:
None | size: 1.59 KB | hits: 17 | expires: Never
jQuery - order DIVs depending on an extracted number of a classname
<div id="list">
<div class="classA classB SORT-4.2"><div>4</div></div>
<div class="classA SORT-3.3"><div>3</div></div>
<div class="classC classD classE SORT-5.1"><div>5</div></div>
<div class="classB classC SORT-1.5"><div>1</div></div>
<div class="classA class B class C SORT-2.4"><div>2</div></div>
</div>
1
2
3
4
5
5
4
3
2
1
arr[0] = {num:4, el:/* the element */}
arr[1] = {num:2, el:/* the element */}
arr[2] = {num:3, el:/* the element */}
function sort( divs, order ) {
var arr = divs.toArray(),
len = arr.length,
parent = divs.parent(),
i = 0;
while( i < len ) {
var num = arr[ i ].className.match(/(?:SORT-([d.]+))/)[1].split('.');
arr[ i ] = {num:num[ order - 1 ],el:arr[ i ]};
i++;
}
arr.sort(function(a,b) {
return a.num - b.num;
});
i = 0;
while( i < len ) {
parent.append( arr[i].el );
i++;
}
}
sort( $('#list > div'), 3 ); // 1,2,3,4,5
$(function(){
function sortDIV(){
var divs=$("div[class*=SORT]").clone();
divs.sort(function(pDiv,fDiv){
var pNumber=parseInt($(pDiv).attr("class").match(/SORT-(.*)/)[1].replace(".",""));
var fNumber=parseInt($(fDiv).attr("class").match(/SORT-(.*)/)[1].replace(".",""));
return pNumber<fNumber;
})
var parent=$($("div[class*=SORT]")[0]).parent();
parent.empty();
divs.each(function(index,div){
$(div).appendTo(parent);
})
}
sortDIV();
})