DIV order based on class name using Javascript / Jquery
I have the following HTML structure:
<div id="container"> <div>1</div> <div class="red">2</div> <div class="red">3</div> <div>4</div> <div>5</div> <div class="red">6</div> <div>7</div> </div> I needed to run JQuery, which sorts the div in the div container, ordering first divs that have class = "red" and then those that don't, so the final structure should be:
<div id="container"> <div class="red">2</div> <div class="red">3</div> <div class="red">6</div> <div>1</div> <div>4</div> <div>5</div> <div>7</div> </div> Help? Thanks.
+4
4 answers
Try the following:
$(function(){ var elem = $('#container').find('div').sort(sortMe); $('#container').append(elem); }); function sortMe(a, b) { return a.className < b.className; } With some fadeIn/fadeout animations
var elem = $('#container').find('div').sort(sortByClass); function sortByClass(a, b) { return a.className < b.className; } var allElem = elem.get(); (function append() { var $this = $(allElem.shift()); $('#container').append( $this.fadeOut('slow')) .find($this) .fadeIn('slow', function () { if (allElem.length > 0) window.setTimeout(append); }); })(); Demo
+16
Add 2 buttons to your html
<button class="sort">SORT</button> <button class="unsort">UNSORT</button> Attach click handlers ...
$('.sort').click(function(){ var elem = $('#container').find('div').sort(doSort); $('#container').append(elem); } $('.unsort').click(function(){ var elem = $('#container').find('div').sort(doUnsort); $('#container').append(elem); } Sort Functions
function doSort(a, b) { return a.className < b.className; } function doUnsort(a, b) { var a = $(a).text().toUpperCase(); var b = $(b).text().toUpperCase(); return (a < b) ? -1 : (a > b) ? 1 : 0; } +3
After the PSL answer did I have to add ? 1 : -1 ? 1 : -1 to the sortMe function as follows:
$(function(){ var elem = $('#container').find('div').sort(sortMe); $('#container').append(elem); }); function sortMe(a, b) { return a.className < b.className ? -1 : 1; // This is the added code } Thanks to Alex and Rejith who answered my similar question How to disable _prevent_ divs in random order
+1
No sorting is required here. Since the elements are already in the order you need, you can simply call prependTo() on them like this:
$('.red').prependTo('#container'); .red { color: #C00; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <div id="container"> <div>1</div> <div class="red">2</div> <div class="red">3</div> <div>4</div> <div>5</div> <div class="red">6</div> <div>7</div> </div> 0