Java – Selenium webdriver – clicking on checkbox based on table value

javajunit4seleniumwebdriver

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>

Best Answer

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.