views:

47

answers:

2

how do i select only 3rd( or some other no. of my chioce) li element with jquery? for ex: how do i change the background of only third li with jquery. any help please

+4  A: 
Sarfraz
Out of curiosity, I fooled around a bit with the selector. As it turns out, using `slice` and act and the whole wrappet set is faster than using `nth-child`. http://www.jsfiddle.net/qbDKN/13/
jAndy
@jAndy: That's clever work :)
Sarfraz
@jAndy - I'm getting opposite results, with `eq` almost twice as slow. Remember `nth-child` is a css selector, and is implemented natively by some browsers.
Kobi
@Kobi: interesting. I tested on Chrome(5) with slightly better results for `slice` (around 300ms).
jAndy
@jAndy - I get about 9400 for `eq`, and about 5800 for `slice`. But wait - in your code, eq **is** the `nth-child` code. How confusing of you :) . So you are right, it is faster.
Kobi
@Kobi: Oh dear, my bad I forgot to rename the `time event`. But wow, sounds like a **big** difference than for you.
jAndy
Also, on the slice code, you don't keep recalling `find` but use the same list, which I suspect skews the results.
Kobi
@Kobi: well true, but it's still realistic. You can't do it otherwise with the `nth-child(xn)` selector.
jAndy
@jAndi - one last note - I also found `background` to be slower than `background-color`, which makes sense when you think about it. It probably takes more than a loop to profile the differences `:|`.
Kobi
+2  A: 

If you need the third li on all lists, use nth-child:

$('li:nth-child(3)')
Kobi
That will select every third child not only
Sarfraz
@Sarfraz - that'd be `nth-child(3n)`
Kobi
I assume I'm being down-voted because Sarfraz edited his answer to include mine, after claiming it isn't correct. Good times.
Kobi
@Kobi: hehe man i didn't down vote you for sure +1 from me though :)
Sarfraz
@Sarfraz - I wasn't suggesting that. Doesn't really matter :)
Kobi