How to add a DIV to every 3 paragraphs (p)

2

Well, what I want is simple. I need to add one div every 3 paragraphs. Remember that these paragraphs will be in another div (in case it would be the content div).

It is similar to that of site , where it is found the announcement.

It would look like this:

<div class="conteudo">
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <div class="anuncio">Div inserida</div>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <div class="anuncio">Div inserida</div>
    <p>&nbsp;</p>
</div>
    
asked by anonymous 19.04.2016 / 21:47

2 answers

5

You can select all p and then use their index within a loop to count / group by three. Adding to that the .insertAfter you have what you need:

$('p').each(function(i) {
    var pos = i + 1;
    if (pos % 3 == 0) {
        $('<div/>', {
            class: 'anuncio',
            text: 'Div inserida!'
        }).insertAfter(this);
    }
});

jsFiddle: link

    
19.04.2016 / 22:03
3

You can use a (an + b) formula in the selector to specify the elements you want to select. In this formula a represents the size cycle, n is a counter (starting at 0), and b is a deviation value.

See more

$div = $('<div class="anuncio">DIV INSERIDA</div>');
$div.insertAfter('.conteudo p:nth-child(3n+0)');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="conteudo">
  <p>PARÁGRAFO</p>
  <p>PARÁGRAFO</p>
  <p>PARÁGRAFO</p>
  <p>PARÁGRAFO</p>
  <p>PARÁGRAFO</p>
  <p>PARÁGRAFO</p>
  <p>PARÁGRAFO</p>
  <p>PARÁGRAFO</p>
  <p>PARÁGRAFO</p>
  <p>PARÁGRAFO</p>
  <p>PARÁGRAFO</p>
  <p>PARÁGRAFO</p>
</div>
    
19.04.2016 / 22:23