Using The :nth-child() Selector In jQuery

This is a very useful function and can be used with a lot of things. I have recently used it with an image gallery I was doing.

I wanted to put some special effects on the first image of a gallery (making it fade in as soon as the page loaded). So you can use it for those kinds of things (images) or just simple text edits or additions. The possibilities are endless with jQuery, half the battle is just knowing what is out there…

I explain it with an example of a very simple way of using it.


   <li>Red Hot Chili Peppers<li>
   <li>Band of Horses</li>
   <li>Cold War Kids</li>
   <li>Death Cab For Cutie</li>
   <li>The Walkmen</li>
   <li>The Strokes</li>


<script type="text/javascript">
 $("ul li:nth-child(2)").append("<span> - Ben Bridwell (vocals and guitar)</span>");

 $("ul li:nth-child(2)").append("<span> - Ben Bridwell (vocals and guitar)</span>")

 $("ul li:nth-child(3)").append("<span> - Nathan Willett (vocals)</span>");

 $("ul li:nth-child(4)").append("<span> - Ben Gibbard (vocals)</span>")

 $("ul li:nth-child(5)").append("<span> - Hamilton Leithauser (vocals)</span>");

 $("ul li:nth-child(6)").append("<span> - Julian Casablancas (vocals)</span>")
 .css('color', '#3A2CB5');

View on Codepen

See the Pen Using The :nth-child() Selector In jQuery by calebnance (@calebnance) on CodePen.