You can make a .each()
by traversing the div
s by checking the value in data-position
of each element.
When you find a value greater than data-position
of div
to be inserted, the loop is canceled with return false;
and the value of the element index coming from (e)
is assigned to the idx
variable.
No if
after the loop you use .before()
to insert div
before element of class .child
whose index is idx
.
If the loop did not find an element with data-position
greater, it means that all have% as data-position
lower, so the value of idx
will remain undefined and 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><divid="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 several ways to enter div
. You can, for example, send to the function only the number of data-position
and mount div
within the function, among others.