Selenium WebDriver - Finding Elements using cssSelector and nth child

Melvin Richard picture Melvin Richard · Nov 26, 2015 · Viewed 67.1k times · Source
<ul>
<li class="active">
    <a href="#">
    <i class="fa fa-home"></i><br>
    <span class="title">Home</span>
    </a>
</li>

<li>
    <a href="#">
    <i class="fa fa-rss-square"></i><br>
    <span class="title">Posts</span>
    </a>
</li>

<li>
    <a href="#">
    <i class="fa fa-calendar"></i><br>
    <span class="title">Events</span>
    </a>
</li>

<li>
    <a href="#">
    <i class="fa fa-bar-chart-o"></i><br>
    <span class="title">My Activity</span>
    </a>
</li>

<li>
    <a href="#">
    <i class="fa fa-edit"></i><br>
    <span class="title">Assessments</span>
    </a>
</li>
</ul>

I want to locate the respective span element. I want to check the order of the span elements using css selector. So when I use selenium IDE,I will verify it like below(using nth child concept).

verifyText | css=.title:nth(0) | Home
verifyText | css=.title:nth(1) | Posts
verifyText | css=.title:nth(2) | Events
verifyText | css=.title:nth(3) | My Activity
verifyText | css=.title:nth(4) | Assessments

But when I do the same thing in Selenium WebDriver I am not able to locate the elements with the order which I did using Selenium IDE.

Below are the codes that I used in WebDriver and it dint work.

driver.findElement(By.cssSelector(".title:nth(0)")); // to locate the "Home" element

driver.findElement(By.cssSelector(".title:nth-of-type(0)")); // to locate the "Home" element

driver.findElement(By.cssSelector(".title:nth-child(0)")); // to locate the "Home" element

Could anyone please help me.

Answer

Mesut GUNES picture Mesut GUNES · Nov 26, 2015

You can generate the css-selector from ul like ul > li:nth-child(1) for home. See below:

driver.findElement(By.cssSelector("ul > li:nth-child(1)")); >> home
driver.findElement(By.cssSelector("ul > li:nth-child(2)")); >> posts
driver.findElement(By.cssSelector("ul > li:nth-child(3)")); >> events

also reachin span is the same:

driver.findElement(By.cssSelector("ul > li:nth-child(1) > a > span")); >> home