I have several divs like this
<div rel="5">
Divs content goes here
</div>
<div rel="3">
Div 3 Here
</div>
<div rel="4">
Div 4 Here
</div>
<div rel="4.5">
Div 4.5 here
</div>
How would you use Jquery to sort the divs so that physically in the DOM they are sorted with the least rel attribute first?
e.g. 3, 4, 4.5, 5
See my fiddle: http://jsfiddle.net/6hpNz/8/
You can leverage a combination of javascript and jQuery to do this pretty easily:
Given the following HTML:
<div class="unsorted">
<div rel="5">
Div 5 here
</div>
<div rel="3">
Div 3 Here
</div>
<div rel="4.5">
Div 4.5 here
</div>
<div rel="4">
Div 4 Here
</div> </div>
<div class="sorted"></div>
This script will give you the desired output:
$(document).ready(function () {
var sortedDivs = $(".unsorted").find("div").toArray().sort(sorter);
$.each(sortedDivs, function (index, value) {
$(".sorted").append(value);
});
});
function sorter(a, b) {
return a.getAttribute('rel') - b.getAttribute('rel');
};
I'm sure there is a much more efficient way, but here is my answer anyway:
HTML:
<div rel="5">
Divs content goes here
</div>
<div rel="3">
Div 3 Here
</div>
<div rel="4">
Div 4 Here
</div>
<div rel="4.5">
Div 4.5 here
</div>
jQuery:
var array = new Array();
$('div').each(function(){
array.push($(this).attr('rel'));
});
array = array.sort();
var reordedDivs = "";
$.each(array, function(i, obj1){
$('div').each(function(j, obj2) {
if ($(obj2).attr('rel') == obj1) {
var divContent = $(obj2).html();
var rel = obj1;
reordedDivs += "<div rel='" + rel + "'>" + divContent + "</div>";
}
});
});
$('body').html(reordedDivs);
Fiddle: http://jsfiddle.net/F6csV/17/
You can select elements with a DOM method, convert DOM list to Array, and then use Array.sort()
.