Interview #167: Selenium - How do you handle dynamic elements?

Interview #167: Selenium - How do you handle dynamic elements?

Handling dynamic elements in Selenium is a common challenge in test automation, especially when working with modern web applications where the structure of elements can change frequently. Dynamic elements are those whose attributes (like id, class, or name) may change each time the page is loaded or after certain user interactions. Selenium provides several strategies and best practices to handle these effectively:

Disclaimer: For QA-Testing Jobs, WhatsApp us @ 91-9606623245

1. Use Dynamic XPath or CSS Selectors

Dynamic elements often have changing attributes, but usually part of the attribute remains constant. You can use XPath or CSS selector functions to target stable parts. Some common techniques include:

  • Using contains() in XPath:

driver.findElement(By.xpath("//input[contains(@id, 'username')]"));        

  • Using starts-with() or ends-with():

driver.findElement(By.xpath("//button[starts-with(@id, 'submit_')]"));        

  • CSS Selectors with partial attribute matches:

driver.findElement(By.cssSelector("input[id*='username']"));        

These allow you to create flexible locators that still uniquely identify the element.


2. Wait for Elements Dynamically (Explicit Waits)

Sometimes, dynamic elements take time to load or appear based on user interactions or AJAX calls. Using explicit waits with conditions like visibilityOfElementLocated or presenceOfElementLocated ensures Selenium waits until the element is available in the DOM.

Example in Java:

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement dynamicElement = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("dynamicElementId")));        

This approach is more reliable than using fixed sleeps (Thread.sleep()), which are inefficient and brittle.


3. Avoid Using Unreliable Attributes

Attributes like id or class that frequently change should be avoided in locators. Instead, focus on:

  • Stable text values
  • Data- attributes (e.g., data-testid, data-name)*
  • Element hierarchy or relationship to other static elements

Example:

driver.findElement(By.xpath("//label[text()='Username']/following-sibling::input"));        

This approach uses a relative path based on a stable label.


4. Use of Custom Wait Logic

In cases where even explicit waits are insufficient (e.g., element appears and disappears quickly), custom polling logic can be implemented:

for (int i = 0; i < 10; i++) {
    try {
        WebElement element = driver.findElement(By.id("dynamicId"));
        if (element.isDisplayed()) {
            break;
        }
    } catch (NoSuchElementException e) {
        Thread.sleep(500);
    }
}        

5. Leverage Page Object Model (POM) and Utilities

In frameworks using POM, dynamic element handling logic can be encapsulated within page classes or utility methods. This promotes reusability and centralized management of dynamic locators.

Example utility method:

public WebElement getDynamicElement(String partialId) {
    return driver.findElement(By.xpath("//*[contains(@id,'" + partialId + "')]"));
}        

6. Use JavaScript Executor (as a last resort)

For elements that are extremely hard to locate or interact with due to frequent DOM changes, JavaScript can be used to interact directly.

Example:

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.querySelector(\"[id*='dynamic']\").click();");        

This method should be used sparingly, as it bypasses WebDriver’s standard mechanisms and may lead to fragile tests.


Conclusion

Handling dynamic elements in Selenium requires a combination of flexible locator strategies, intelligent waits, and well-structured code. By using techniques such as dynamic XPath/CSS selectors, explicit waits, and avoiding unstable attributes, you can ensure your test scripts remain robust and maintainable even when the application under test changes frequently.

Article content


Laxman Sapkale 🔍

QA Engineer | 3700-Linkedin 👨👩👧👦| Software Tester | Manual & Automation Tester | Java Selenium | Improved Regression Test Coverage by 60%| Helping IT Companies Succeed| (Guided 137K+ Learners Through QA Content ).

2mo

Excellent approach! These two – driver.findElement(By.xpath("//button[starts-with(@id, 'submit_')]) and JavaScriptExecutor – can be effectively utilized for locating elements. Found this valuable and very useful.

Like
Reply

To view or add a comment, sign in

Others also viewed

Explore topics