Select a row element based on another row element in Selenium

Viewed 54

I want to select a checkbox based on another element in the row in Selenium. Eg: How do I select the checkbox corresponding to Cricket?

<body>
    <table id="MyTable">
        <tbody>
            <tr>
                <td>
                    <input type="checkbox" />
                </td>
                <td>Football</td>
            </tr>
            <tr> 
                <td>
                    <input type="checkbox" />
                </td>
                <td>Cricket</td>
            </tr>
        </tbody>
    </table>
</body>
2 Answers

Try the following xpath:

driver.findElement(By.xpath("//table[@id='MyTable']//tr[contains(., 'Cricket')]//input[@type='checkbox']")).click();

See check boxes in general are input tag, you if you want to select that using Cricket keyword, you can use the below xpath :

//td[text()='Cricket']/preceding-sibling::td/input

and in code :-

driver.findElement(By.xpath("//td[text()='Cricket']/preceding-sibling::td/input")).click();

or

you could try with Explicit waits as well :

new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//td[text()='Cricket']/preceding-sibling::td/input"))).click();
Related