qwertymk
qwertymk

Reputation: 35256

is there a css selector for this?

I have one or two divs on the page with a class/classes of foo. I need to select the second one only, that means if there's only one on the page don't select it.

I tried div.foo:not(:first) and div.foo:nth-child(2) and both don't seem to work.

Any ideas?

Upvotes: 1

Views: 291

Answers (2)

BoltClock
BoltClock

Reputation: 723428

There isn't an :nth-of-class() selector, but if both div.foo elements share the same parent, you can use one of the sibling selectors depending on whether the second div.foo comes immediately after the first or not:

div.foo + div.foo /* Is immediately after */
div.foo ~ div.foo /* Is somewhere after among its siblings */

If there are potentially more than two such divs, you may need to undo the styles in the above rule using one of these for any subsequent elements:

div.foo + div.foo ~ div.foo
div.foo ~ div.foo ~ div.foo

And don't worry about browser support, this works in IE7+.

Upvotes: 4

Sivvy
Sivvy

Reputation: 851

It depends on a few things. Are you testing on IE? Are the elements inside the same parent?

If the elements aren't inside the same parent, I'm not sure they can use those particular selectors, and as far as I can remember, they don't currently work in IE (excluding sibling selectors, and not sure about IE9+).

Upvotes: 0

Related Questions