Reputation: 7971
I have disorder div in HTML page and that need to in ascending order based on their id. I have some code but it is not working I just want to know what is wrong with code or do i need to do some more work with code. fiddle
Jquery
$('div').sort(function (a, b) {
var contentA =parseInt( $(a).attr('data-sort'));
var contentB =parseInt( $(b).attr('data-sort'));
return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
})
HTML
<div data-sort='14'>14</div>
<div data-sort='6'>6</div>
<div data-sort='9'>9</div>
Upvotes: 0
Views: 1977
Reputation: 489
Given that your data is integer based and the sort you need is ascending order, there is a neat way to do this with pure css :)
Just put your data divs inside a parent flexbox container and make your sort integer a css order property, like so...
<div id="container" style="display:flex">
<div style="order:14">14</div>
<div style="order:6">6</div>
<div style="order:9">9</div>
</div>
Only works in 'modern' browsers though.
Upvotes: 1
Reputation: 5040
Check this out: http://jsfiddle.net/en107qxb/5/
function sortUsingText(parent, childSelector) {
var items = parent.children(childSelector).sort(function(a, b) {
var vA = $(a).text();
var vB = $(b).text();
return (vA < vB) ? -1 : (vA > vB) ? 1 : 0;
});
parent.append(items);
}
sortUsingText($('#sortThis'), "div");
function sortUsingData(parent, childSelector) {
var items = parent.children(childSelector).sort(function(a, b) {
var vA = $(a).data('sort');
var vB = $(b).data('sort');
return (vA < vB) ? -1 : (vA > vB) ? 1 : 0;
});
parent.append(items);
}
sortUsingData($('#sortThisData'), "div");
HTML
<div id="sortThis">
<div>3</div>
<div>1</div>
<div>2</div>
</div>
<div id="sortThisData">
<div data-sort="7">High</div>
<div data-sort="2">Low</div>
<div data-sort="5">Mid</div>
</div>
Upvotes: 0
Reputation: 82241
Use:
var asc=false;
var sorted=$('div').sort(function(a,b){
return (asc ==
($(a).data('sort') < $(b).data('sort'))) ? 1 : -1;
});
asc = asc ? false : true;
$('body').html(sorted);
Upvotes: 1