user3872094
user3872094

Reputation: 3351

Loop through Rows and click

I've the below HTML table.

 <table>
        <tr>
            <td>Link 1</td>
            <td>Archieved</td>
        </tr>
        <tr>
            <td>Link 2</td>
            <td>Terminated</td>
        </tr>
        <tr>
            <td>Link 3</td>
            <td>Active</td>
        </tr>
        <tr>
            <td>Link 4</td>
            <td>Archieved</td>
        </tr>
    </table>

Here basically i want to loop through all the rows and click only if the content in second row doesn't contain Terminated.

In XSLT i use to use xsl:for-each select but in Selenium I'm unable to understand how to do this. Please let me know how i can click on the rows that doesn't contain Terminated.

Thanks

Upvotes: 2

Views: 652

Answers (2)

drkthng
drkthng

Reputation: 6909

Here is how you can loop through all rows, click the ones that do not match "Terminated" as text and do whatever you like with the other rows:

List<WebElement> allRows = driver.findElements(By.xpath("//table/tr"))

for (WebElement row : allRows) {
    if (!row.findElement(By.xpath("./td[2]")).getText().contains("Terminated")) {
        row.click();
    }
    // get whatever you need from the rows here
}

Upvotes: 2

alecxe
alecxe

Reputation: 473833

You may filter out rows not containing "Terminated" with a single XPath expression:

//tr[td[2] != 'Terminated']

Here is how you may loop through the elements matching a selector:

for(WebElement row: driver.findElements(By.xpath("//tr[td[2] != 'Terminated']"))) {
    // do smth with a row
}

Upvotes: 2

Related Questions