javascript – Is it possible to create a map to place elements?


I would like to know if it is possible to "preset" the position of an element when using an append , for example:

<div id="mainDiv">
   <div class="child" data-position="2"></div>
   <div class="child" data-position="6"></div>
   <div class="child" data-position="7"></div>
   <div class="child" data-position="9"></div>

Now after a certain user action let's say I need to use the following append :

$("#mainDiv").append('<div class="child" data-position="5"></div>');

By default the element will be added to the end of the current content of div#mainDiv , however I would like to create a function that detects in which position such element should be added which in this case would be between childs 2 and 6.


You can do an .each() traversing the div s checking the data-position of each element.

When finding a value greater than the data-position of the div to be inserted, the loop is canceled with return false; and the element index value coming from (e) is assigned to the variable idx .

On if after the loop you use .before() to insert the div before the class element .child whose index is idx .

If the loop has not found an element with data-position higher data-position , it means that they all have a lower data-position value, so the idx value idx remain undefined and the 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);

// chama a função passando a div a ser inserida
add('<div class="child" data-position="5">5</div>');
<script src=""></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>

There are several ways to insert the div . You can, for example, send to the function just the data-position and assemble the div inside the function, among others.

Scroll to Top