Dynamic Locator Keeps Changing on Refresh
Dynamic Locator Keeps Changing on Refresh
Key Takeaways & Cheat Sheet
- βAvoid dynamic attributes (like auto-generated IDs or class names)
- βIdentify a stable custom data-attribute (e.g., data-testid, data-qa)
- βBuild smart Relative XPath using contains(), starts-with() or text()
- βUtilize relative parent-child-sibling relationships in DOM tree
- βCollaborate with developers to add stable hooks for testing
Short Direct Answer
Dynamic elements are extremely common in modern frameworks (React, Angular, Vue) where class names or IDs are auto-generated on load (e.g., id="btn-submit_9a7c3"). A professional automation engineer identifies the root cause and bypasses these dynamic properties by leveraging stable custom attributes, utilizing relative XPath axes, or using text-matching selectors rather than brittle auto-generated values.
β οΈ Senior Warning (Red Flag)
Never hardcode dynamic IDs (like btn_4920a) or rely on absolute XPath paths starting from the html root. They will break your test suite on every backend deployment or slight DOM modification.
π‘ STAR Deep Dive Explanation & Pro Tip
If no stable attributes exist, always inspect the DOM for surrounding static elements. Connect to them first as an anchor, and navigate to the target element using axes like following-sibling, parent, or descendant.
// β brittle dynamic ID: driver.findElement(By.id("btn-submit_9a7c3"));
// β
Best practice: Locate using custom data-attributes
WebElement submitBtn = driver.findElement(By.xpath("//button[@data-testid='submit-login']"));
// β
Sibling Strategy: Locate an input field based on its stable text label
WebElement emailField = driver.findElement(By.xpath("//label[text()='Email']/following-sibling::input"));
// β
Match Partial Dynamic Properties using XPath functions
WebElement partialBtn = driver.findElement(By.xpath("//input[contains(@id, 'login-btn_')]"));