sandrooco
sandrooco

Reputation: 8776

Sort divs in specific order

I'm trying to sort divs (identified with a data attribute) in a specific row:

<div id="sortablesParent">
  <div class="sortable" data-key="1"></div>
  <div class="sortable" data-key="2"></div>
  <div class="sortable" data-key="3"></div>
  <div class="sortable" data-key="4"></div>
</div>

Now, I got an array:

var order = ["4", "2", "3", "1"];

As you could expect, the output HTML should look like this:

<div id="sortablesParent">
  <div class="sortable" data-key="4"></div>
  <div class="sortable" data-key="2"></div>
  <div class="sortable" data-key="3"></div>
  <div class="sortable" data-key="1"></div>
</div>

I have no clue on how to do this. I already tried to do something with jQuery.sort(), couldn't really find a good approach though. Of course I had a look on similar questions, these couldn't help me though.

Upvotes: 1

Views: 247

Answers (1)

Andrew Brooke
Andrew Brooke

Reputation: 12173

.sort will work, but since the divs are already in the DOM, you should save the sorted divs into a variable, and put them back into the parent div after sorting.

var order = ['4', '3', '2', '1'];

var html = $('#sortablesParent div').sort(function(a, b) {
  var l = $.inArray($(a).attr('data-key'), order);
  var r = $.inArray($(b).attr('data-key'), order);
  return (l < r) ? -1 : (l > r) ? 1 : 0;
});

$('#sortablesParent').html(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sortablesParent">
  <div class="sortable" data-key="4">4</div>
  <div class="sortable" data-key="2">2</div>
  <div class="sortable" data-key="3">3</div>
  <div class="sortable" data-key="1">1</div>
</div>

Upvotes: 4

Related Questions