Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery nth-child selector problem

I want to select images in a div. The images i want are number 2,5,8,11 etc.

$('.thediv img:nth-child(3n+1)').. 

Did not work for me, did i miss something? Thanks

like image 386
fille Avatar asked Dec 01 '25 14:12

fille


1 Answers

Your formula 3n + 1 doesn't work because these are the elements that will be selected for the following values of n:

3(0) + 1 = 0 + 1 = 1
3(1) + 1 = 3 + 1 = 4
3(2) + 1 = 6 + 1 = 7
3(3) + 1 = 9 + 1 = 10
...

Clearly, these aren't the 2nd, 5th, 8th, 11th ... elements selected. Each of them is off by 1. You need to use the formula 3n + 2 instead, so these elements will be selected:

3(0) + 2 = 0 + 2 = 2
3(1) + 2 = 3 + 2 = 5
3(2) + 2 = 6 + 2 = 8
3(3) + 2 = 9 + 2 = 11
...

And since you said in your comment that each img is in an a, the :nth-child() pseudo-class should be attached to a, then you select the img:

$('.thediv a:nth-child(3n+2) img')
like image 63
BoltClock Avatar answered Dec 03 '25 04:12

BoltClock