Can make a .each()
traversing the div
checking the value in data-position
of each element.
When you find a higher value than the data-position
of div
to be inserted, the loop is canceled with return false;
and the value of the element index from (e)
is assigned to the variable idx
.
In the if
after the loop you use .before()
to insert the div
before the class element .child
whose index is in idx
.
If the loop has not found an element with data-position
larger, means that all have value in data-position
smaller, hence the value of idx
will continue indefinite and will div
will be inserted at the end with .append()
:
function add(div){
var pos = $(div).data('position'); // pega o valor do data-position
var idx;
$("#mainDiv .child").each(function(e){
if($(this).data('position') > pos){
idx = e; // idx pega o valor do índice encontrado
return false; // aborta o loop
}
});
if(idx >= 0){
// O ":eq()" seleciona o elemento pelo índice (base zero)
// No caso, a div com o valor data-position "6" é de índice 1
$("#mainDiv .child:eq("+idx+")").before(div);
}else{
$("#mainDiv").append(div);
}
}
// chama a função passando a div a ser inserida
add('<div class="child" data-position="5">5</div>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mainDiv">
<div class="child" data-position="2">2</div>
<div class="child" data-position="6">6</div>
<div class="child" data-position="7">7</div>
<div class="child" data-position="9">9</div>
</div>
There are various ways to insert the div
. You can, for example, send to the function only the number of the data-position
and mount the div
within the function, among others.