Search code examples
jquerycss-selectorsinsertafter

Inject div inbetween two divs using nth-child and .after?


I have a bunch of divs, which are being outputted via PHP which all contain images. I have a lone div that I want to inject after the 4th div, but I'm having issues achieving this. I am using Isotope to grid the images/divs.

An example of my jQuery:

$('.each-brewery-image:nth-child(4n)').after('<div>Test</div>');

An example of my HTML:

<div class="each-brewery-image">
   <a class="fancybox" rel="gallery1" href="#">
   <span>
       <img width="700" height="524" src="01.jpg" />
   </span>
   </a>
</div>
<div class="each-brewery-image">
   <a class="fancybox" rel="gallery1" href="#">
   <span>
       <img width="700" height="524" src="02.jpg" />
   </span>
   </a>
</div>
<div class="each-brewery-image">
   <a class="fancybox" rel="gallery1" href="#">
   <span>
       <img width="700" height="524" src="03.jpg" />
   </span>
   </a>
</div>

Solution

  • :nth-child(4n) selects the 5th, 9th, 13th, etc. elements. You probably want :eq():

    $('.each-brewery-image:eq(3)').after('<div>Test</div>');
    

    :eq() and :nth-child() are zero-indexed, so :eq(0) is the first item, :eq(1) is the second, etc.