Ziska
Ziska

Reputation: 153

Cannot find the nth element on the page using nth-child and WebDriver

I have a form that has 4 calendar Widgets. The html source is the same for all the widgets.

<div class="grid_12">
<td class="wikicell">
    <div class="Item">
        <div class="Value">
            <input type="hidden" id="Submit_Date$_type" value="Date,99/99/9999">
            <input id="Submit_Date" size="40" value="" type="text">
            <a href="javascript:" class="Calendar">
                <img src="transparent.gif" class="Placeholder" tabindex="-1" align="absmiddle">
            </a>
        </div>
    </div>
</td>

I am able to locate the first calendar using the following code:

driver.findElement(By.cssSelector("div.grid_12 img.Placeholder"), 15).click();

But when I try to located the 2nd, 3rd and 4th calendars using nth-child(2)/(3) or (4) I get an "Unable to locate element: {"method":"css selector","selector":"div.grid_12 img.Placeholder:nth-child(2)"}

I also tried with "a.Calendar", "div.grid_12 img" work too for the first calendar. These 3 selectors can successfully click and open the first calendar widget when used with "nth-child(1)" but not for the next 3.

I used Thread.sleep(3000) after the first calendar is closed but I end up getting the same error.

I used findElements() method to get all the calendar widgets and double check using size() to check if the WebDriver is locating all calendar elements. The result is 4 as expected.

Am I not using 'nth-child' correctly?

Upvotes: 1

Views: 4000

Answers (1)

Ziska
Ziska

Reputation: 153

I first located the form/table that has these calendar icons and called findElement() on this element as a reference to find the respective calendars. Here's the solution -

WebElement form = uiHelper.waitForElementPresent(By.cssSelector("table.left tbody"), 15);
//Enter time
form.findElement(By.cssSelector("tr:nth-child(3) td:nth-child(2) img")).click();
form.findElement(By.cssSelector("tr:nth-child(4) td:nth-child(2) img")).click();

Upvotes: 4

Related Questions