Jquery - Add element to each certain amount of other elements

Asked

Viewed 69 times

1

I need to add a tag breaking (<br> or <hr>) each quantity of <div> dynamically arising.

For PHP, i group 10 records by <div>, that is, every 10 records creates a <div> to start collecting the new results, thus:

<div class="grupo">
    <?php foreach($qr->result() as $key => $resultado){
        if ($key % 10 === 0) {
            echo "</div><div class=\"grupo\">";
        } 
    }// foreach ?>
</div>
<!--/.grupo-->

Then after 3 <div class="grupo"> created, the break should be inserted (<br> or <hr>).

By PHP I can’t, so I’m trying by Jquery. I believe it’s with for, appendTo and anything else that I have no idea what it is or how to do.

1 answer

0


With jQuery, traversing the elements of the class .grupos, you can add a <hr> always after the third element using .each():

$(function(){

   $(".grupo").each(function(i){

      // "i" é o índice dos elementos na coleção
      // como começa com 0, soma +1 para iniciar de 1 a contagem
      var c = i+1;

      // a cada grupo de 3, adiciona um "hr" após
      if(c % 3 == 0) $(this).after("<hr>");

    });

});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.