1

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?

1
  • :first is a jQuery selector. It does not exist in CSS. Commented Oct 28, 2011 at 21:12

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

Also only works if they are both contained in the same parent.
If your div.foo elements don't share the same parent, then you'll have to use jQuery with your first selector, as in $('div.foo:not(:first)').
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.