When working with Selenium automation, we may sometimes encounter issues with dynamic web elements. Dynamic elements are those whose properties or attributes change each time the application is loaded or refreshed. In many cases, these elements do not have unique identification attributes such as id, name, or class, making them difficult to locate using standard Selenium locators. To handle such elements effectively, we can use techniques like dynamic XPath, CSS selectors, relative XPath, or explicit waits based on the application’s behavior.
We can use XPath or CSS Selectors to identify dynamic elements in Selenium. In the example below, I have a nested unordered list that does not contain unique attributes such as id, name, or class.
To locate the “Laptops” link within this nested list below , we can use a relative XPath, for example:
//ul/li/ul/li/a[normalize-space()='Laptops']
Nested List
<ul id="mainMenu">
<li>
<a href="#" id="electronics" title="Electronics Category">Electronics</a>
<ul>
<li><a href="#" title="Laptop Products">Laptops</a></li>
<li><a href="#" title="Mobile Phones">Mobiles</a></li>
<li><a href="#" title="Tablet Devices">Tablets</a></li>
<li><a href="#" title="iPod Music Devices">iPod</a></li>
</ul>
</li>
<li><a href="#" id="furniture" title="Furniture Category">Furniture</a></li>
<li><a href="#" id="books" title="Books Category">Books</a></li>
<li><a href="#" id="fashion" title="Fashion Items Category">Fashion Items</a></li>
</ul>
This XPath starts from an unordered list (ul), navigates to its child list item (li), then to another nested unordered list (ul), followed by another list item (li), and finally selects the anchor (a) element whose visible text is “Laptops”.
By using relative XPath expressions based on the element hierarchy, we can reliably locate dynamic elements even when they do not have unique attributes such as id or class. This is a common and effective approach for handling dynamic elements in Selenium automation.
Find the HTML page containing dynamic elements for demonstration purposes using the link below. Automation Demo: Dynamic HTML Elements Practice Page
Below is the Selenium Java script to locate the “Laptops” link.
Example Code:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeSuite;
public class VerifyElements {
WebDriver driver;
@Test
public void validateLinks() {
driver = new ChromeDriver();
driver.get("https://yourwebsite.com");
WebElement elem = driver.findElement(By.xpath("//ul/li/ul/li/a[normalize-space()='Laptops']"));
elem.click();
}
}
Watch YouTube Video here: Handling Dynamic elements in selenium