1

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.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
dushkin
  • 1,939
  • 3
  • 37
  • 82

2 Answers2

2

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:

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • 1
    If you are trying to automate a user scenario, you should (generally) prefer the Selenium click vs the JSE click because JSE can click all kinds of things a user can't like invisible elements, etc. – JeffC May 01 '19 at 21:25
0

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();
S Ahmed
  • 1,454
  • 1
  • 8
  • 14
  • Why a `cssSelector` under the heading of `XPath`? – undetected Selenium May 01 '19 at 21:02
  • Your XPath is missing the opening `//`. `ol[day-tabs]` should be `ol.day-tabs` in the CSS selector. Also, neither of these will work because you have "n" as a string instead of passing in a variable `n`. – JeffC May 01 '19 at 21:23
  • I've fixed the code. It was a mistake I made when I tried to format the code and then I mixed it up in the editor. – S Ahmed May 02 '19 at 06:23