I'd like to be able to sort a bunch of div
elements on my page with the click of a button.
All of them have simple text content, for example:
<div class='sortme'>
CCC
</div>
<div class='sortme'>
AAA
</div>
<div class='sortme'>
BBB
</div>
<div class='sortme'>
DDD
</div>
When the user clicks a button, they should be rearranged in alphabetical order. Obviously there's a number of ways to do this, most obviously we can get all the contents into an array, sort the array and recreate the HTML based on that.
This is an example of such a solution:
http://jsfiddle.net/hibbard_eu/C2heg/
However, this wouldn't play nice with a lot of code already being used, and I was hoping to be able to simply move the divs around without doing anything destructive. Is this possible?
$('.sortme').sort(function(a, b) {
if (a.textContent < b.textContent) {
return -1;
} else {
return 1;
}
}).appendTo('body');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class='sortme'>
CCC
</div>
<div class='sortme'>
AAA
</div>
<div class='sortme'>
BBB
</div>
<div class='sortme'>
DDD
</div>
Can be done pretty simply even without jQuery
function sortThem(s) {
Array.prototype.slice.call(document.body.querySelectorAll(s)).sort(function sort (ea, eb) {
var a = ea.textContent.trim();
var b = eb.textContent.trim();
if (a.textContent < b.textContent) return -1;
if (a.textContent > b.textContent) return 1;
return 0;
}).forEach(function(div) {
div.parentElement.appendChild(div);
});
}
// call it like this
sortThem('div.sortme');
element.appendChild(x) adds x as the last child of element, if x exists in the DOM, it is moved from it's current location, so, no need for any gymnastics to remove it in one place and add it in t'other
Use append.
var $divs = $("div.box");
$("div.box").on("click", function (e) {
alert("I'm an original");
});
$('#alphBnt').on('click', function () {
var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
return $(a).find("h1").text() > $(b).find("h1").text();
});
alphabeticallyOrderedDivs.each(function (i, item) {
$("#container").append(item);
});
});
$('#numBnt').on('click', function () {
var numericallyOrderedDivs = $divs.sort(function (a, b) {
return $(a).find("h2").text() > $(b).find("h2").text();
});
numericallyOrderedDivs.each(function (i, item) {
$("#container").append(item);
});
});
Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With