ReasonPlay ReasonPlay - 3 months ago 5
Javascript Question

Adding div and sort in same time

I want to add my div to others and sort in the same based on

data-sort
value.

Example:

<div id="divbox">
<div class="somediv" data-sort="0.10">some content</div>
<div class="somediv" data-sort="0.05">some content</div>
</div>


And how to add another div to
divbox
with value
data-sort="0.7"
and i should be placed between two div's how I can do these.

Answer

Use append() to append new html contents to an element. For ordering use sort() method and for reflecting it into the dom append in new order using appendTo() method.

// get the parent div
$('#divbox')
  // append new div to it
  .append('<div class="somediv" data-sort="0.07">some content</div>')
  // get all children divs
  .children()
  // sort the object collection based on data-sort value
  .sort(function(a, b) {
    // get difference for sorting based on number
    return $(b).data('sort') - $(a).data('sort');
    // append back to parent for updating order
  }).appendTo('#divbox');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divbox">
  <div class="somediv" data-sort="0.10">some content</div>
  <div class="somediv" data-sort="0.05">some content</div>
</div>


Or you can iterate over children and insert div based on the comparison of the attribute value.

// create jQuery object of append content
var $ele = $('<div class="somediv" data-sort="0.07">some content</div>');
// get sort value of it
var dataVal = +$ele.data('sort');

// iterate over existing divs
$('#divbox .somediv').each(function(i) {
  // get sort value of current element
  var thisVal = +$(this).data('sort');
  // if sort value is greter than the first div then append the element before it
  if (i == 0 && dataVal > thisVal) {
    // append before first element
    $ele.insertBefore(this);
    // break the for loop 
    return false;
    // if the element is last or satisfies the codition for insertion
  } else if ($(this).next().length == 0 || (datVal <= thisVal && thisVal > +$(this).next().data('sort'))) {
    // insert the eleemnt 
    $ele.insertAfter(this);
    // break the loop
    return false;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divbox">
  <div class="somediv" data-sort="0.10">some content</div>
  <div class="somediv" data-sort="0.05">some content</div>
</div>

Comments