1

I have a page with a 'ul' (unordered list) that I insert 'li' elements on the fly. With 2 attributes: data-col and data-row. This two attributes are arbitrary and can be any value. (any Real positive number)

Is there a way to re-order all 'li' elements based on data-row and data-col? It does not have to be visible, I just need the 'ul' element with all its children properly ordered.

Extra info: The reason for this is because I have a back-end code that needs to read this 'ul' element with its children in sequence and then populate a TABLE element. It´s like I´m saving a multi-dimensional array into a 1 dimension array.

Thanks :)

4
  • Wouldn't it be easier to sort the data you're sending to the backend, and not the elements themselves ? Maybe you should post some of the code, or at least a few examples of what it would look like ? Commented Apr 23, 2015 at 0:02
  • 1
    Are the rows/columns even ? If you have any code that you're kicking around it would be easier to assist! Commented Apr 23, 2015 at 0:02
  • @adeneo I´m using a grid framework so it´s kinda big code, as I insert new things to the grid, the framework adds a new 'li' to the 'ul' element. But it does not rearrange it, it adds to the bottom of the list. I haven´t thought about reorder it in backend, I just thought it would be easy to reorder it in javascript. I will try it but I´d still like to know how to do it in javascript. Commented Apr 23, 2015 at 0:11
  • @zfrisch No, max columns are 4 but the rows are variable Commented Apr 23, 2015 at 0:11

1 Answer 1

3

You can use jQuery.sort() to sort the list of li elements based on row, then column, and re-append the sorted list to the ul. The appended list replaces the 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 are the same, sort by 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>

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, that was perfect! Thanks Paul!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.