javascript - Sort unordered list based on data-row and data-col -


i have page 'ul' (unordered list) insert 'li' elements on fly. 2 attributes: data-col , data-row. 2 attributes arbitrary , can value. (any real positive number)

is there way re-order 'li' elements based on data-row , data-col? not have visible, need 'ul' element children ordered.

extra info: reason because have back-end code needs read 'ul' element children in sequence , populate table element. it´s i´m saving multi-dimensional array 1 dimension array.

thanks :)

you can use jquery.sort() sort list of li elements based on row, column, , re-append sorted list ul. appended list replaces previous unsorted version:

var ul = $('#mylist');    var lis = $('#mylist > li');    lis.sort(      function(a, b) {      var ela = $(a);      var elb = $(b);            var res = +ela.data('row') - elb.data('row');            if (res == 0)   // if rows same, sort column        res = +ela.data('col') - elb.data('col');            return res;    }    ).appendto(ul);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>    <ul id="mylist">    <li data-col="2" data-row="14">14, 2</li>    <li data-col="2" data-row="1">1, 2</li>    <li data-col="3" data-row="4">4, 3</li>    <li data-col="1" data-row="3">3, 1</li>    <li data-col="1" data-row="4.5">4.5, 1</li>  </ul>


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -