tags:

views:

457

answers:

5

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).

+1  A: 

Selectors can be combined:

.bar:nth-child(2)

means "thing that has class bar" that is also the 2nd child.

geocar
A: 

What exactly is the structure of your HTML?

The previous CSS will work if the HTML is as such:

CSS

.foo:nth-child(2)

HTML

<div>
 <div class="foo"></div>
 <div class="foo"Find me</div>
...

But if you have the following HTML it will not work.

<div>
 <div class="other"></div>
 <div class="foo"></div>
 <div class="foo">Find me</div>
 ...

Simple put, there is no selector for the getting the index of the matches from the rest of the selector before it.

Seamus
If I can't do it by index, is there a way to get the last item in a matched group? Since there are only 2 in this case I know that the 2nd is also the last.
mpeters
+1  A: 

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...

Stein G. Strindhaug
Seems that since there was no way to do this in just CSS I resorted to using Javascript. Thanks.
mpeters
A: 

Is there a reason that you can't do this via Javascript? My advice would be to target the selectors with a universal rule (.foo) and then parse back over to get the last foo with Javascript and set any additional styling you'll need.

Or as suggested by Stein, just add two classes if you can:

<div class="foo"></div>
<div class="foo last"></div>

.foo {}
.foo.last {}
One Crayon
A: 

If you're gonna use javascript, then I recommend you to use jquery instead.

facildelembrar