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.
Compare chained findElement calls with a single, smarter locator.
This lesson focuses on two different ways to reach the same element in Selenium:
Both are valid. The question is: When should you use which?
WebElement parent = driver.findElement(...);
WebElement child = parent.findElement(...);WebElement element = driver.findElement(
By.cssSelector("#parent-id .child-class")
);#header .login-btn).Picture a "Shop" section with different lists and one special demo card.
○ State is OFF
id="shop"id="vegetables"id="fruits"id="lesson5-optimized-card"class="opt-action"If you use the page like a normal user:
1234567WebElement container = driver.findElement(By.id("lesson5-optimized-card"));
WebElement btnNested = container.findElement(By.className("opt-action"));
WebElement btnOptimized = driver.findElement(By.cssSelector("#lesson5-optimized-card .opt-action"));
btnOptimized.click();
driver.quit();id. This is one WebDriver command (one round-trip).container element, searches inside it for a child with class="opt-action". This is a second WebDriver command. Useful if you plan to reuse container or btnNested.id and child class in one CSS selector. The browser finds "any element with .opt-action that lives inside #lesson5-optimized-card" in a single WebDriver command.btnNested and btnOptimized refer to the same button; we use the optimized one for the final interaction.If the element is part of a reusable component, prefer nested lookups with a clear "root" element. If it's a one-off interaction, use a short, optimized CSS like #card-id .action-btn.
Reducing WebDriver calls is good, but never at the cost of unreadable locators. Aim for clean + fast, not just clever.
Decide a team convention (e.g., "use nested lookups in Page Objects, optimized selectors in quick utilities") so your tests stay predictable and maintainable.