Some locators are not static — they depend on runtime data like product names, user IDs, or row numbers. For these, create parameterized methods that build the locator dynamically.
public class CatalogPage extends BasePage {
// Dynamic locator — built at runtime
public void clickProduct(String productName) {
By locator = By.xpath(
"//div[@class='product-card']" +
"[.//span[text()='" + productName + "']]");
click(locator);
}
public String getProductPrice(String productName) {
By locator = By.xpath(
"//div[@class='product-card']" +
"[.//span[text()='" + productName + "']]" +
"//span[@class='price']");
return getText(locator);
}
// For table rows with dynamic IDs
public void clickRow(int rowIndex) {
By locator = By.cssSelector(
"table tbody tr:nth-child(" + rowIndex + ")");
click(locator);
}
// For elements with dynamic IDs like "product-123"
public void selectProduct(String productId) {
By locator = By.id("product-" + productId);
click(locator);
}
}The key pattern: the locator is built inside the method using the parameter. The test calls clickProduct("Laptop Pro") and the page object constructs the XPath internally. The test never sees the locator.
Q: How do you handle dynamic elements in POM?
A: I create parameterized methods that build locators at runtime. For example, clickProduct(String productName) constructs an XPath with the product name as a parameter. The test passes the product name, the page object builds and uses the locator internally. I also use explicit waits to handle elements that appear asynchronously.
Key Point: Build locators dynamically inside page object methods. The test passes data, the page builds the locator.