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).
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 .
myclass:eq(1)" ) selects the second element in the document with the class myclass, rather than the first. In contrast, :nth-child(n) uses 1-based indexing to conform to the CSS specification. Prior to jQuery 1.8, the :eq(index) selector did not accept a negative value for index (though the . eq(index) method did).
The element+element selector is used to select an element that is directly after another specific element.
Simple selectors (select elements based on name, id, class) Combinator selectors (select elements based on a specific relationship between them) Pseudo-class selectors (select elements based on a certain state)
Selectors can be combined:
.bar:nth-child(2)
means "thing that has class bar" that is also the 2nd child.
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? :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With