dushkin
dushkin

Reputation: 2111

Selenium Chrome webdriver Java: How to select n-th list item?

I have the following element:

<ol class="day-tabs">
    <li class="current"><a href="date1.html">a</a></li>
    <li class=""><a href="date2.html">b</a></li>
    <li class=""><a href="date3.html">c</a></li>
</ol>

As you may see, only the first list item has a class definition. What I need is to go to the n-th item in the list.

So it is not a problem to do:

WebElement days_tabs = chromeWebDriver.findElement(By.className("day-tabs"));
        

and then:

ArrayList<WebElement> listItems = new ArrayList<>(days_tabs.findElements(By.tagName("li")));

but when I tried

    JavascriptExecutor ex = (JavascriptExecutor)chromeWebDriver;
    ex.executeScript("arguments[0].click();", listItems.get(n));

I didn't see that the n-th item was selected.

Upvotes: 1

Views: 522

Answers (2)

S A
S A

Reputation: 2040

If you are not trying to access all the <li> elements, you can use the selector for the nth element directly.

XPath:

WebElement nthElement = driver.findElement(By.xpath("ol[@class='day-tabs']/li[n]"));
nthElement.click();

CSS SElector:

WebElement nthElement = driver.findElement(By.cssSelector("ol.day-tabs > li:nth-of-type(n)"));
nthElement.click();

Upvotes: 0

alecxe
alecxe

Reputation: 474003

You may need to do the actual click via selenium API and not via JavaScript:

listItems.get(n).click();

There are some substantial differences between the two as outlined here:

Upvotes: 2

Related Questions