πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Scenarios
Scenario 1 of 100
Locators
Intermediate

Dynamic Locator Keeps Changing on Refresh

πŸ”„Scenario Overview

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.

SeleniumAutomation.java
Selenium 4 + Java
// ❌ 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_')]"));