We use cookies to analyze site traffic and show personalized ads. You can accept all cookies or decline personalized advertising.
Learn more in our Privacy Policy.
A summary of core concepts, best practices, and common pitfalls when finding elements in Selenium.
Finding elements is more than just writing a locator. It involves understanding the DOM structure, managing scope, and handling dynamic content.
NoSuchElementException if not found.element.findElement(...) to search inside a specific parent, ignoring the rest of the page.getShadowRoot() to pierce through encapsulation boundaries.driver.switchTo().activeElement() to find where the focus is.findElements(...).isEmpty(). Never use findElement for negative assertions because it throws an exception.This script demonstrates finding a list of products, scoping the search to each product card, and handling the Shadow DOM.
12345678910111213141516171819// 1. Find all product cards (returns a List)
List<WebElement> products = driver.findElements(By.className("product-card"));
System.out.println("Found " + products.size() + " products.");
for (WebElement product : products) {
// 2. Scoped Search: Find title INSIDE this specific card
// Note: The locator starts from 'product', not 'driver'
WebElement title = product.findElement(By.tagName("h3"));
System.out.println("Product: " + title.getText());
// 3. Shadow DOM interaction (if the 'Buy' button is in a shadow root)
WebElement shadowHost = product.findElement(By.cssSelector("custom-buy-button"));
SearchContext shadowRoot = shadowHost.getShadowRoot();
// Find the actual button inside the shadow root
WebElement buyBtn = shadowRoot.findElement(By.cssSelector("button.primary"));
buyBtn.click();
}product-card. If none match, the loop simply doesn't run.product variable. This limits the search to children of that specific card.If the DOM updates (e.g., after a filter is applied), your old WebElement references become "stale". Always re-find elements after a page update.
Instead of driver.findElement(By.id("a")).findElement(By.className("b")), prefer a single CSS selector: driver.findElement(By.cssSelector("#a .b")). It's faster.
findElement fails immediately if the element isn't there. In real tests, combine this with Explicit Waits (covered in future units) to handle loading times.