0
votes

i am currently working java/selenium webdriver automation. However i am stuck at this particular part which i am unable to make the webdriver click on the checkbox based on a value.

driver.findElement(By.xpath("//input[@class='chkPopupCod']/following::td[contains(text(),'BBB')]")).click();

It works when i did not use the Axes part of xpath, however it can only select the first checkbox

Below is a snippet of the html

<tr class="even">
<td style="width: 20px;">
<input class="chkPopupCod" type="checkbox">codData=Object { id=101914, codId=101906, label="AAA", more...}
</td>
<td class="" align="left">AAA</td>
</tr>
<tr class="odd">
<td style="width: 20px;">
<input class="chkPopupCod" type="checkbox" style="background-color: rgb(255, 255, 255);">codData=Object { id=101918, codId=101907, label="BBB", more...}
</td>
<td class="" align="left" style="background-color: transparent;">BBB</td>
</tr>
<tr class="even">
<td style="width: 20px;">
<input class="chkPopupCod" type="checkbox">codData=Object { id=101922, codId=101908,   label="CCC", more...}
</td>
<td class="" align="left">CCC</td>
</tr>
3

3 Answers

2
votes

You have the right idea in your XPath. Just flip it around:

//td[contains(text(),'BBB')]/preceding::td/input[@class='chkPopupCod']

As in, get that element that has the text inside it first. Make your way through the tree after that.

0
votes

When working with tables I always like to first identify which table row I am working on. For this, I have a method to return me the table row and then from there I start looking for the element I wish to use.

Example: Method to get the parent table row -

    public void IWebElement GetParentTableRow(IWebElement element)
    {
        while (!element.TagName.ToLower().Equals("tr"))
        {
            try
            {
                element = element.FindElement(By.XPath("..")); //Returns the parent
            }
            catch
            {
                return null;
            }
        }

        return element;
    }

Usage -

public void Test()
{
   IWebElement tableRow = GetParentTableRow(driver.FindElement(By.XPath("//td[contains(text(),'BBB')]"));
   tableRow.FindElement(By.ClassName("chkPopupCod")).Click();
}

Hope it helps. :)

0
votes

Although the original question pertained to the Java version of of WebDriver, if anyone reading this is working in .NET, there is an extension called TableDriver (https://github.com/jkindwall/TableDriver.NET) that would help with things like this. The original question does not show the full html of the table, so I can't be sure exactly how it would apply, but you should be able to do something like this:

Table table = Table.Create(driver.FindElement(By.Id("tableId")));
table.FindCell("\1=BBB", 0).Element.Click();

Update

TableDriver.Java is now available. Details here: https://github.com/jkindwall/TableDriver.Java