Abe Miessler
Abe Miessler

Reputation: 85046

How to select the second element with a certain class?

Let me start by saying that I am aware of nth-child and as far as I can tell this will not work in my situation. Say I have the HTML below:

<div>
    <div class="myclass">test1</div>
</div>
<div>
    <div class="myclass">test2</div>
</div>
<div>
    <div class="myclass">test3</div>
</div>

And I want to highlight the div that contains test2. From what I understand using .myclass:nth-child(2) will not work because it is looking for the second child instance of myclass and all the instances I have are first child. You can see this not working here.

So my question is how can I select the second instance of myclass from the above example using only CSS3? I can't use javascript/jquery.

Upvotes: 0

Views: 98

Answers (3)

Hylianpuffball
Hylianpuffball

Reputation: 1561

To follow imjared's answer, you might want to change how you think about the DOM... from your original question, it sounds like you're trying to get the second instance of .myclass to change, but CSS can't really look globally for all instances before and after.

Instead, I would think of it like this:

<some containing Element, like body> div:nth-of-type(2) .myclass {
    color: red;
}

What you're really trying to select is the .myclass element in the second section of some containing element. The code in your question only works if the .myclass elements are direct siblings, which they aren't.

Upvotes: 0

meobyte
meobyte

Reputation: 1320

div:nth-of-type(2) > .myclass{
    background-color:red;
}

A tiny bit more robust.

Upvotes: 0

imjared
imjared

Reputation: 20554

This should do it:

div:nth-of-type(2) .myclass {
    background:pink !important;
}

or

div:nth-child(3) .myclass {
    background:pink !important;
}

Upvotes: 3

Related Questions