Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering DIVs based on class name using Javascript/Jquery

Tags:

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 wast to run some Jquery that will sort the divs inside the div container by ordering the divs first 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.

like image 993
Callum Avatar asked Jun 10 '13 05:06

Callum


3 Answers

Try this:

 $(function(){
   var elem = $('#container').find('div').sort(sortMe);
   $('#container').append(elem);
 });

 function sortMe(a, b) {
        return a.className < b.className;
  }

Demo

With Some fadeIn/fadeout animation

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

like image 145
PSL Avatar answered Nov 08 '22 00:11

PSL


Sorting is not required here. As the elements are already in the order you need, you can just 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>
like image 4
Rory McCrossan Avatar answered Nov 08 '22 02:11

Rory McCrossan


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);
}

Sorting 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;
}

JS FIDDLE DEMO

like image 3
Kylie Avatar answered Nov 08 '22 00:11

Kylie