Adrian Florescu
Adrian Florescu

Reputation: 4492

jQuery - After number of elements add html!

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

<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>

Upvotes: 3

Views: 2706

Answers (3)

miku
miku

Reputation: 188014

Take a look at the nth-child-selector.

Basically:

$("#wrapper a:nth-child(3n)").after("<span>I'm new.</span>");

Upvotes: 6

Vadim
Vadim

Reputation: 17957

$('#wrapper a').each(function(index) {
  if ((index+ 1) % 3 == 0)
     $(this).after(content);
});

Upvotes: 3

Brad Christie
Brad Christie

Reputation: 101604

$('#wrapper a').each(function(i,e){
  if (((i+1) % 3) == 0)
    $(this).after('<p>Hello, world.</p>');
});

Take advantage of .each's "i" parameter that gives you element index. Than you can use Modulo to get the 3rd item and append.

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

at this point just showing an alternative solution

Upvotes: 7

Related Questions