Skip to content
Advertisement

Selecting Nth-of-type in selenium

I’m trying to use By.cssSelector to grab the nth dom element with class c3 with a structure like this:

<div class="c1">
    <div class="c2">
        <div class="c3">...</div>
    </div>
</div>
<div class="c1">
    <div class="c2">
        <div class="c3">...</div>
    </div>
</div>
<div class="c1">
    <div class="c2">
        <div class="c3">...</div>
    </div>
</div>

Testing my CSS selectors, I’m becoming increasingly confused. This selector selects the 2nd instance of c2/c3 correctly:

.c1:nth-of-type(2) 

while:

.c2:nth-of-type(2)
.c3:nth-of-type(2)

select nothing.

Even worse, translating this into selenium, I seem to consistently find nothing for all 3 versions. There are plenty of alternative ways to select these elements (I’ll probably just do XPATH), but my lack of understanding on nth-of-type is driving me crazy. Can anyone offer insight to why the second 2 don’t work or correct my basic lack of comprehension on this selector?

This has been in Chrome (29/30) and Firefox (24/25)

Advertisement

Answer

I’m not enirely sure which one you want to select, but you should play around more with the :nth-* pseudo-classes. Here is a CSS selector that selects all 3 c3’s using nth-child()

div.c1 div.c3:nth-child(1)

Like i said, you haven’t really specified which one you want to select.

but my lack of understanding on nth-of-type is driving me crazy. Can anyone offer insight to why the second 2 don’t work or correct my basic lack of comprehension on this selector?

One thing to keep in mind, is all of the :nth-*() pseudo-classes are dependent on their parents. Let me translate your selector:

.c1:nth-of-type(2)

Find anything with a class of c1 that is a second child.

In your case, <body> was most likely the parent, so…

<body>
  <div .c1 />
  <div .c1 /> // it highlights this one, because it's the 2nd child of the type ".c1"
  <div .c1 />
</body>

Now let me explain why your other selectors are not working.

Both .c2:nth-of-type(2) and .c3:nth-of-type(2) are looking at the parent’s as well. since you are specifying a parent, it’s expecting <body> as the parent. In your case, <body> isn’t the parent.. the <div .c1 /> is. In reality, that selector is looking for the DOM –

<body>
  <div .c1 />
  <div .c2 /> // this **would** be the second nth-of-type, but it's not really this way. 
  <div .c1 />
</body>

Play around with the different css selectors and pseudo-classes at http://cssdesk.com it’s very helpful to actively experiment on your own. you’ll figure it out.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement