Careeroza
Dynamic Elements and DevTools
Attributes That Change
Some frameworks generate ids such as input-8f3a2 or react-select-17-option-2 that change on every load or build. A locator using the full id passes once and fails tomorrow.
| Problem | Fix |
|---|---|
id="btn-checkout-83412" | //button[starts-with(@id,'btn-checkout-')] or [id^='btn-checkout-'] |
id="cart-83412-count" | [id$='-count'] or contains(@id,'-count') |
| no stable attribute at all | use the label or text: //label[text()='Pincode']/following-sibling::input |
Building Locators at Runtime
Example
A locator can be built from test data with String.format. This prints the XPath used for each product name:
public class Main {
static String addToCartFor(String productName) {
return String.format("//h3[normalize-space()='%s']/ancestor::div[@class='product-card']//button[@id='add-to-cart']", productName);
}
public static void main(String[] args) {
for (String name : new String[] {"Nike Revolution 7", "Puma Velocity Nitro"}) {
System.out.println(addToCartFor(name));
}
}
}Output
//h3[normalize-space()='Nike Revolution 7']/ancestor::div[@class='product-card']//button[@id='add-to-cart'] //h3[normalize-space()='Puma Velocity Nitro']/ancestor::div[@class='product-card']//button[@id='add-to-cart']
Tip: Methods like addToCartFor(name) make one locator serve every product. You will use this pattern in page objects.
Test Locators in Chrome DevTools
- Open ShopEase in Chrome and press F12 (DevTools).
- Right-click an element → Inspect to see its HTML.
- In the Elements tab press Ctrl+F and type a CSS selector or XPath. DevTools highlights matches and shows "1 of 1".
- Or use the Console tab:
$$(".product-card")for CSS,$x("//h3")for XPath.
Console Output
Example
In the DevTools Console:
$$(".product-card").length
$x("//td[text()='ORD-1002']/following-sibling::td[1]")[0].innerTextExample output
24 'Shipped'
Note: Aim for exactly 1 of 1 match for a single element. "1 of 3" means Selenium will pick the first one, which may not be the one you want.
Tip: Avoid "Copy XPath" from DevTools when it gives an absolute path or an auto-generated id. Write your own short relative locator.