mpeters - 10 months ago 50
CSS Question

# CSS3 selector to find the 2nd div of the same class

I need a CSS selector that can find the 2nd div of 2 that has the same class. I've looked at

nth-child()
but it's not what I want since I can't see a way to further clarify what class I want. These 2 divs will be siblings in the document if that helps.

My HTML looks something like this:

<div class="foo">...</div>
<div class="bar">...</div>
<div class="baz">...</div>
<div class="bar">...</div>


And I want the 2nd div.bar (or the last div.bar would work too).

UPDATE: This answer was originally written in 2008 when nth-of-type support was unreliable at best. Today I'd say you could safely use something like .bar:nth-of-type(2), unless you have to support IE8 and older.

Original answer from 2008 follows (Note that I would not recommend this anymore!):

If you can use Prototype JS you can use this code to set some style values, or add another classname:

// set style:
$$('div.theclassname')[1].setStyle({ backgroundColor: '#900', fontSize: '1.2em' }); // OR add class name:$$('div.theclassname')[1].addClassName('secondclass'); // pun intentded...


(I didn't test this code, and it doesn't check if there actually is a second div present, but something like this should work.)

But if you're generating the html serverside you might just as well add an extra class on the second item...