1

I am using the code from this question sort div elements in a variable. It works perfectly, but rather than storing the div elements in a variable I need to sort them on page.

The div elements will hold a long menu hence wanting to sort divs on page rather than in a variable.

Community
  • 1
  • 1
projectmonkey
  • 69
  • 1
  • 12

1 Answers1

1

So for your code instead of using an variable use a jQuery selector.

Basic idea on sorting

$("li").sort( function (a,b) { 
  return $(a).text() > $(b).text();
}).appendTo("ul");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>C</li>
  <li>A</li>
  <li>B</li>
</ul>

With divs

$(".wrapper div").sort( function (a,b) { 
  return $(a).text() > $(b).text();
}).appendTo(".wrapper");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <div>C</div>
  <div>A</div>
  <div>B</div>
</div>

and indexOf with ids...

var sortOrder = "Train,Car,Bus";

$(".wrapper div").sort( function (a,b) { 
  return sortOrder.indexOf(a.id) > sortOrder.indexOf(b.id);
}).appendTo(".wrapper");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <div id="Car">C</div>
  <div id="Bus">A</div>
  <div id="Train">B</div>
</div>
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • Thanks epascarello. I have used a similar idea with indexOf, but not working on IE. How would this work with divs? – projectmonkey Feb 04 '16 at 16:41
  • Should work no differently with divs. Append to the parent – epascarello Feb 04 '16 at 16:42
  • Thank you. I need to set the sort order via a variable. – projectmonkey Feb 04 '16 at 16:48
  • So do it like you did in the other question, instead of using a variable, select the elements.... – epascarello Feb 04 '16 at 16:51
  • I should have used Order by rather than Sort. I want to achieve something like this http://stackoverflow.com/questions/16283734/how-to-sort-div-elements-according-to-id-from-a-csv-list-using-jquery – projectmonkey Feb 04 '16 at 16:52
  • indexOf doesn't work in IE so moved onto the solution in my question which works perfect except that the divs need to be on page. – projectmonkey Feb 04 '16 at 17:07
  • I am not sure how indexOf does not work in IE... But I am not sure why you can not figure out how to take $('
    ', {html:html}) and change it to point to the element that holds your divs.
    – epascarello Feb 04 '16 at 17:11