Skip to main content
SeleniumDecoded

Find a Table Row by Cell Text and Act on It

Locate the row that contains a given value, then read or click another cell in the same row, using a header lookup instead of hard-coded column numbers.

Stable Verified against Selenium 4.52.0

Problem

An orders table lists hundreds of rows. You need the row for order ORD-1042, then read its Status cell or click its Edit button. Row positions change with sorting and new data, so tr[7] breaks constantly. Column positions change too when someone adds a column.

Solution

Find the row by the text of one of its cells, then find the target column’s index from the header row. Locating relative to the row keeps everything inside one record.

Row by key, cell by header name
Selenium 3 & 4 Stable
public static WebElement rowByCellText(WebDriver driver, By table, String text) {
// normalize-space() trims and collapses whitespace in the cell
return driver.findElement(table).findElement(
By.xpath(".//tbody/tr[td[normalize-space()='" + text + "']]"));
}
public static int columnIndex(WebDriver driver, By table, String header) {
List<WebElement> headers = driver.findElement(table).findElements(By.cssSelector("thead th"));
for (int i = 0; i < headers.size(); i++) {
if (headers.get(i).getText().trim().equalsIgnoreCase(header)) return i + 1; // XPath is 1-based
}
throw new NoSuchElementException("No column named " + header);
}
By orders = By.id("orders");
WebElement row = rowByCellText(driver, orders, "ORD-1042");
int statusCol = columnIndex(driver, orders, "Status");
String status = row.findElement(By.xpath("./td[" + statusCol + "]")).getText();
row.findElement(By.cssSelector("button[aria-label='Edit']")).click();
def row_by_cell_text(driver, table, text):
return driver.find_element(*table).find_element(
By.XPATH, f".//tbody/tr[td[normalize-space()='{text}']]")
def column_index(driver, table, header):
headers = driver.find_element(*table).find_elements(By.CSS_SELECTOR, "thead th")
for i, th in enumerate(headers, start=1): # XPath is 1-based
if th.text.strip().lower() == header.lower():
return i
raise NoSuchElementException(f"No column named {header}")
orders = (By.ID, "orders")
row = row_by_cell_text(driver, orders, "ORD-1042")
status_col = column_index(driver, orders, "Status")
status = row.find_element(By.XPATH, f"./td[{status_col}]").text
row.find_element(By.CSS_SELECTOR, "button[aria-label='Edit']").click()
async function rowByCellText(driver, table, text) {
return (await driver.findElement(table)).findElement(
By.xpath(`.//tbody/tr[td[normalize-space()='${text}']]`));
}
async function columnIndex(driver, table, header) {
const headers = await (await driver.findElement(table)).findElements(By.css('thead th'));
for (let i = 0; i < headers.length; i++) {
if ((await headers[i].getText()).trim().toLowerCase() === header.toLowerCase()) return i + 1;
}
throw new Error(`No column named ${header}`);
}
const orders = By.id('orders');
const row = await rowByCellText(driver, orders, 'ORD-1042');
const statusCol = await columnIndex(driver, orders, 'Status');
const status = await row.findElement(By.xpath(`./td[${statusCol}]`)).getText();
await row.findElement(By.css("button[aria-label='Edit']")).click();
public static IWebElement RowByCellText(IWebDriver driver, By table, string text) =>
driver.FindElement(table).FindElement(By.XPath($".//tbody/tr[td[normalize-space()='{text}']]"));
public static int ColumnIndex(IWebDriver driver, By table, string header)
{
var headers = driver.FindElement(table).FindElements(By.CssSelector("thead th"));
for (int i = 0; i < headers.Count; i++)
if (string.Equals(headers[i].Text.Trim(), header, StringComparison.OrdinalIgnoreCase))
return i + 1; // XPath is 1-based
throw new NoSuchElementException($"No column named {header}");
}
var orders = By.Id("orders");
var row = RowByCellText(driver, orders, "ORD-1042");
var statusCol = ColumnIndex(driver, orders, "Status");
var status = row.FindElement(By.XPath($"./td[{statusCol}]")).Text;
row.FindElement(By.CssSelector("button[aria-label='Edit']")).Click();

Why It Works

The XPath predicate tr[td[normalize-space()='ORD-1042']] selects the tr whose child cell has that exact text, regardless of where the row sits. Every later lookup starts from that row element with a relative path (./td, or a CSS selector called on the row), so you cannot accidentally read a cell from a neighbouring record. The header lookup turns a column name into an index at runtime, so adding or reordering columns does not break the test.

Variations

NeedXPath
Key in a specific column.//tbody/tr[td[2][normalize-space()='ORD-1042']]
Partial match.//tbody/tr[td[contains(normalize-space(), 'ORD-10')]]
Key inside a link or span.//tbody/tr[td[.//a[normalize-space()='ORD-1042']]]
Two conditions.//tbody/tr[td[normalize-space()='Alice'] and td[normalize-space()='Pending']]
Cell in the same row, one step.//tr[td[normalize-space()='ORD-1042']]/td[4]

Gotchas

  • Quotes in data. A value containing ' breaks the XPath string. Use concat() to build the literal, or prefer a data-testid on the row if you can ask the developers for one.
  • Virtualised grids (AG Grid, MUI DataGrid, react-window) only render visible rows. If the row is off-screen it is not in the DOM; filter the grid by the key first, or scroll the grid viewport until the row appears.
  • Div-based grids use role="row" and role="gridcell" instead of tr/td. The same idea works: .//*[@role='row'][.//*[@role='gridcell' and normalize-space()='ORD-1042']].
  • Duplicates. If the key is not unique, findElement silently returns the first match. Use findElements and assert the count is 1 when uniqueness matters.
  • Header text with sort icons. getText() may include hidden icon text or a trailing arrow. Compare with startsWith or read a data-column attribute if headers have one.

Learn the theory