I'm using $('div').css('color', 'red');
but I want the 5th div in my code to have red text. How would I do this?
Asked
Active
Viewed 67 times
0

David G
- 94,763
- 41
- 167
- 253
-
have you tried using .each()? – Christopher Pelayo Feb 14 '12 at 01:23
4 Answers
4
$('div:eq(4)').css('color', 'red')
the :eq selector takes a 0-based integer

Vigrond
- 8,148
- 4
- 28
- 46
-
I always use the function thinking that is better for performance but I haven't tested it `$('div').eq(4).css('color', 'red')` Imma run a jsPerf and see... – elclanrs Feb 14 '12 at 01:27
-
1Indeed, the `:eq` selector is way slower than the `eq()` function. [jsPerf Test](http://jsperf.com/eq-selector-vs-eq-function-in-jquery) – elclanrs Feb 14 '12 at 01:29
-
For speed, `getElementsByTagName` runs rings around any jQuery equivalent. – RobG Feb 14 '12 at 03:14
0
To answer the title question, if the particular element is named foo, you would use $('#foo')
.

John Pick
- 5,562
- 31
- 31
0
You can use the :eq jQuery selector. See jsFiddle here:
Also see this SOq:

Community
- 1
- 1

icyrock.com
- 27,952
- 4
- 66
- 85
0
POJS:
document.getElementsByTagName('div')[5].style.color = 'red';
It might be boring, but it's 20 to 30 times faster than the jQuery equivalent in IE 8.

RobG
- 142,382
- 31
- 172
- 209