Reputation: 4492
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
Reputation: 188014
Take a look at the nth-child-selector.
Basically:
$("#wrapper a:nth-child(3n)").after("<span>I'm new.</span>");
Upvotes: 6
Reputation: 17957
$('#wrapper a').each(function(index) {
if ((index+ 1) % 3 == 0)
$(this).after(content);
});
Upvotes: 3
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