budi
budi

Reputation: 6551

Selector for locating the second element not within the same parent

Given the following HTML:

<div>
    <span class="my-class">One</span>
</div>
<div>
    <span class="my-class">Two</span>
</div>

Can I use a CSS Selector using the class attribute my-class to locate only the second span
(<span class="my-class">Two</span>)? Note that the <span>s are in different <div>s.

I've tried .my-class:nth-child(2) and .my-class:nth-of-type(2), which do not work. Also if possible, I would like to avoid using XPaths.

Upvotes: 1

Views: 682

Answers (3)

Michael Benjamin
Michael Benjamin

Reputation: 371231

With the :nth-child and :nth-of-type pseudo-class selectors you are targeting siblings. In other words, the elements must have the same parent.

.my-class:nth-child(2) and .my-class:nth-of-type(2) will not work as expected because you are targeting the second element inside the div container, which doesn't exist.

Since both divs are siblings (children of body), consider targeting the second div:

div:nth-child(2) > .my-class

Upvotes: 1

ffguven
ffguven

Reputation: 185

An addition to @koala_dev 's answer, if you want to avoid using XPaths, you can give id attribute to each span to catch them. If you are using a script language, you can print your <span>'s by using a loop and you can set id's of each to loop variable. For example

#span-2{
  background:red;
  }
<div>
       <span class="my-class" id="span-1">One</span>
    </div>
    <div>
       <span class="my-class" id="span-2">Two</span>
    </div>

Upvotes: -2

omma2289
omma2289

Reputation: 54629

You need to use :nth-child to target the second div and then find the class you want inside it:

div:nth-child(2) .my-class{
  background: red;
}
<div>
    <span class="my-class">One</span>
</div>
<div>
    <span class="my-class">Two</span>
</div>

Upvotes: 2

Related Questions