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

Css

Css Problem Overview


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

Css Solutions


Solution 1 - Css

Selectors can be combined:

.bar:nth-child(2)

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

Solution 2 - Css

My original answer regarding :nth-of-type is simply wrong. Thanks to Paul for pointing this out.

The word "type" there refers only to the "element type" (like div). It turns out that the selectors div.bar:nth-of-type(2) and div:nth-of-type(2).bar mean the same thing. Both select elements that [a] are the second div of their parent, and [b] have class bar.

So the only pure CSS solution left that I'm aware of, if you want to select all elements of a certain selector except the first, is the general sibling selector:

.bar ~ .bar

http://www.w3schools.com/cssref/sel_gen_sibling.asp


My original (wrong) answer follows:

With the arrival of CSS3, there is another option. It may not have been available when the question was first asked:

.bar:nth-of-type(2)

http://www.w3schools.com/cssref/sel_nth-of-type.asp

This selects the second element that satisfies the .bar selector.

If you want the second and last of a specific kind of element (or all of them except the first), the general sibling selector would also work fine:

.bar ~ .bar

http://www.w3schools.com/cssref/sel_gen_sibling.asp

It's shorter. But of course, we don't like to duplicate code, right? :-)

Solution 3 - Css

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

Solution 4 - Css

HTML

<h1> Target Bar Elements </h1>

<div class="foo">Foo Element</div>
<div class="bar">Bar Element</div>
<div class="baz">Baz Element</div>
<div class="bar">Bar Second Element</div>
<div class="jar">Jar Element</div>
<div class="kar">Kar Element</div>
<div class="bar">Bar Third Element</div>

CSS

.bar {background:red;}
.bar~.bar {background:green;}
.bar~.bar~.bar {background:yellow;}

DEMO https://jsfiddle.net/ssuryar/6ka13xve/

Solution 5 - Css

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

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

Solution 6 - Css

And for people who are looking for a jQuery compatible answer:

$('.foo:eq(1)').css('color', 'red');

HTML:

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

Solution 7 - Css

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 {}

Solution 8 - Css

.parent_class div:first-child + div

I just used the above to find the second div by chaining first-child with the + selector.

Solution 9 - Css

First you must select the parent element and set :nth-of-type(n) for the parent and then select the element you want. something like this :

#topmenu li:nth-of-type(2) ul.childUl {

This will select the second submenu from topmenu. #topmenu li is the parent element.

HTML:

<ul id="topmenu">
    <li>
        <ul class="childUl">
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </li>
    <li>
        <ul class="childUl">
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </li>
    <li>
        <ul class="childUl">
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </li>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmpetersView Question on Stackoverflow
Solution 1 - CssgeocarView Answer on Stackoverflow
Solution 2 - CssmhelvensView Answer on Stackoverflow
Solution 3 - CssStein G. StrindhaugView Answer on Stackoverflow
Solution 4 - CssSurya R PraveenView Answer on Stackoverflow
Solution 5 - CssSeamusView Answer on Stackoverflow
Solution 6 - CssTimonView Answer on Stackoverflow
Solution 7 - CssOne CrayonView Answer on Stackoverflow
Solution 8 - CssEric HendricksonView Answer on Stackoverflow
Solution 9 - Cssamir22View Answer on Stackoverflow