How can i search text and click opposite button

I’m trying to find a text and click opposite button. Texts is dynamic . Texts and buttons are different xpath.

If there’s a one-to-one relationship between the text elements and the buttons, then the index position of the target text element will also serve to target the associated button. That’s one way.

If you know ahead of time the index of the text element, that will cut your job in half.

Sorry, but without some HTML to help see what’s going on, that’s the best I can do.

Yes, there is a one-to-one relationship between the text elements and the buttons. But how can i do index position of the target text element ? will also serve to target the associated button.
I don’t know index of the text element

As Russ says, without some HTML, we don’t know enough to give you a specific answer. However, sometimes the page may be done in a table, so the two elements would be on the same row (review info on web tables) sometimes the page may be done in repeating groups so the path to one is similar to the other (array-wise), and sometimes the Y position of one is close to the Y position of another (use position methods). And more info will help us help you.


sample.html (1.6 KB)

Sample Text area xpath : //*[@id=“dvCustomerList”]/div/div/table/tbody/tr[7]/td[1]/text()

Sample Button xpath : //*[@id=“dvCustomerList”]/div/div/table/tbody/tr[7]/td[3]/div/div/button

Sorry, I don’t see what your issue is.

Your xpath is targeting a <tr> with index value 7. The other xpath is also targeting tr 7 to find the button. That is exactly what I suggested you do.

If you need to loop over the table rows, read about it here:

Create object with xpath
//tr[./td[contains(text(), “ADEM DOGAN”) or contains(. , “ADEM DOGAN”)]]/td/button

First of all thank you for your help. I can now click the button. But I’m getting an error. How can i fix this error ?
Reason: org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document

My script :
String ExpectedValue = findTestData(‘04-ELogoSiparisKayit’).getValue(4, 3)

WebDriver driver = DriverFactory.getWebDriver()

WebElement Table = driver.findElement(By.xpath(’//table/tbody’))

List Rows = Table.findElements(By.tagName(‘tr’))

println('No. of rows: ’ + Rows.size())

for (int i = 0; i < Rows.size(); i++) {
List Cols = Rows.get(i).findElements(By.tagName(‘td’))

for (int j = 0; j < Cols.size(); j++) {
     
	if (Cols.get(j).getText().equalsIgnoreCase(ExpectedValue)) {
         Cols.get(2).findElement(By.tagName('button')).click()
        
		 break
    }
}

}

Just a guess, when you click the button, the page/table/cells change. That means the old Test Objects have been destroyed giving you stale elements, as you’ve seen.

Read this message from @Brandon_Hein – it appears at the bottom of the thread in the link I gave you: