JQuery - after the number of elements add html!

I need to know if I can count the elements inside a div and add an html object after three elements.

<div id="wrapper">
<a href="#">1</a>
<a href="#">1</a>
<a href="#">1</a>
//insert html with jQuery here
<a href="#">1</a>
<a href="#">1</a>
<a href="#">1</a>
//insert html with jQuery here
<a href="#">1</a>
<a href="#">1</a>
<a href="#">1</a>
//insert html with jQuery here
</div>
+3
source share
3 answers
$('#wrapper a').each(function(i,e){
  if (((i+1) % 3) == 0)
    $(this).after('<p>Hello, world.</p>');
});

Use the .each"i" option , which gives you the index of the item. Than you can use Modulo to get the 3rd element and add.

Working example: http://www.jsfiddle.net/hd7FP/1/

at that moment an alternative solution is just shown

+6
source

Take a look at nth-child-selector .

Basically:

$("#wrapper a:nth-child(3n)").after("<span>I'm new.</span>");
+5
source
$('#wrapper a').each(function(index) {
  if ((index+ 1) % 3 == 0)
     $(this).after(content);
});
+3
source

Source: https://habr.com/ru/post/1785624/


All Articles