How do I sort a div?

I have a div table as for a page, is it possible to sort it as an html table with javascript?

I switched from a regular table because I was unable to continue using it because of this How do I add td rowspans to the table? and thus use a div table.

so I used this div table and the only thing I missed was how to make it sortable so that I can sort by item or price. For example datatables, tablesorter etc

<div class="Header">    
    <div class="item"><a href="#">Item</a>
    </div>
    <div class="desc"><a href="#">Description</a>
    </div>      
    <div class="price"><a href="#">Price</a>
    </div>    
    <div class="status"><a href="#">Status</a>
    </div>
</div>

<div class="Info">
  <div class="itemName">
    <div class="item">Item 1</div>
  </div>
  <div class="itemInfo">
    <div class="List">
      <div class="Desc">Description 1</div>
      <div class="Box">                
        <div class="price">$79</div>
        <div class="status">16 in stock</div>
      </div>
    </div> 
  </div>
</div>

      

full code here http://codepen.io/anon/pen/empqyN?editors=110 and here http://jsfiddle.net/a4fcxzra/

+3


source to share


2 answers


Here is the sorting handler: (header classes should be the same as info, so have changed in desc header for Desc)

var sorting=1;
$(".Header div").each(function(){
    $(this).click(function(){
        var cl=$(this).attr("class") // get header class, this is where I get info from
        sorting = sorting == 1 ? -1 : 1 ;         // sorting asc or desc
        $(".Info").detach().sort(function(a,b){
            var str1=$(a).find('.'+cl).text(); // get text
            var str2=$(b).find('.'+cl).text();
            var n1 = str1.match(/\d+/)[0] //get digits in text
            var n2 = str2.match(/\d+/)[0]
            if(n1 != '' ){ // if its a number
                return n1*sorting > n2*sorting; // sort by number
            }else{ // sort by string
                return sorting == 1 ? str1 > str2 : str1 < str2
            }
        }).appendTo($(".Header").parent());
    })
})

      



Working fiddle: http://jsfiddle.net/juvian/a4fcxzra/1/

+2


source


You can sort the array using JavaScript and then dynamically create tags to put them on the column headers (which you should create in html for best performance).



0


source







All Articles