I'm testing an application and in the application there is a table containing checkboxes (3 rows, x columns). Below is the html for part of this table (1row). I'm trying to click on the text of one of these items to either select or deselect a checkbox based on the text. So for example, I want to click on the text 'Text next to checkbox for nr 8' in order to select that textbox. However, I don't want to go there via a hard xpath using code like /table/tbody/tr[2]/td[2]/div/span)[2] but based on the text. I'm trying code like the ones below but they don't seem to work:
driver.findElement(By.xpath("(//*[@class='settingsPanelTD' and text()='Text next to checkbox for nr 8']")).click();
driver.findElement(By.xpath("(//*[@class='settingswidgetTitle' and text()='Text next to checkbox for nr 8']")).click();
driver.findElement(By.xpath("(//*[@class='settingswidgets' and text()='Text next to checkbox for nr 8']")).click();
I would like to create a string for the final xpath so you only have to change the text you'd like to click to change the test, something like:
String text = "Text next to checkbox for nr 8"; /** variable text based on what you want to click */
String locator = "//*[@class='settingswidgets' and text()='";
String xpathitem = locator + text + "']";
driver.findElement(By.xpath(xpathitem)).click();
This is the HTML:
<td class="settingsPanelTD" width="33%">
<div class="settingwidgetsTitle">
<input id="widgetsettings8" class="settingwidgets" type="checkbox" alt="2">
<span>Text next to checkbox for nr 8</span>
<a class="AddWidget" href="#"></a>
</div>
</td>
<td class="settingsPanelTD" width="33%">
<div class="settingwidgetsTitle">
<input id="widgetsettings9" class="settingwidgets" type="checkbox" alt="2">
<span>Text next to checkbox for nr 9</span>
<a class="AddWidget" href="#"></a>
</div>
</td>
<td class="settingsPanelTD" width="33%">
<div class="settingwidgetsTitle">
<input id="widgetsettings9" class="settingwidgets" type="checkbox" alt="2">
<span>Text next to checkbox for nr 10</span>
<a class="AddWidget" href="#"></a>
</div>
</td>
I'm using eclipse, Selenium and Java.