Explain Codes LogoExplain Codes Logo

How can I check if an element exists with Selenium WebDriver?

java
prompt-engineering
best-practices
webdriver
Anton ShumikhinbyAnton Shumikhin·Jan 12, 2025
TLDR

Use the mixture of findElements() and isEmpty() to swiftly check for element presence in Selenium WebDriver. This avoids the need for exceptions and set up an uncomplicated boolean check.

Simple version:

boolean isElementExistent = !driver.findElements(By.id("SomeId")).isEmpty();

This line of code will give you true if your element is on the page, and false if it's not.

Upgrade insights and optimization

To boost the effectiveness of the basic answer, you can incorporate the various methods for checking the existence of an element to make your tests more robust and easier to manage.

Speedy checks with implicit waits

To speed up your existence checks, you can temporarily set the implicit wait to zero. Like ordering a pizza and telling them you have all day, then calling them every two minutes to ask where your pepperoni delight is.

driver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS); // "I'm cool, take your time!" boolean isElementFound = !driver.findElements(By.id("SweetId")).isEmpty(); // "Where's my pizza?!" driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS); // "Oh, there it is."

Multipurpose utility methods (because we hate repeating!)

Creating multipurpose utility methods can help us combat code repetition:

public boolean doesElementExist(WebDriver driver, By by) { return !driver.findElements(by).isEmpty(); // Eagle has landed }

Extending WebDriver and WebElement because we can!

Consider extending IWebDriver and IWebElement to grow their potential:

public class SafeWebDriver extends WebDriver { // I am your *better* WebDriver now! boolean doesElementExist(By by) { // "Frankly, my dear, I don't give a `NoSuchElementException`." // Implement using previous utility method } } public class SafeWebElement extends WebElement { // Because `NoSuchElementException` is just too mainstream! boolean elementExists() { // "You exist because I allow it. And you will end because I demand it." // Custom implementation } }

Steady balance between waits and checks

A few techniques can help to play with waiting times and checking for element existence.

Shun exception handling

Steer clear of try-catch for NoSuchElementException because it's just too not cool for this use case, man.

// NoSuchElementException? Haven't heard that name in years... boolean doesElementExist = !driver.findElements(By.id("elementId")).isEmpty();

Fixed stare on the loading page

Custom methods should respect the page's personal time, especially if it's a lazy loader. In such cases, explicit waits can be your new best friend:

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); // Relax, take it easy boolean doesElementExist = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("elementId"))) != null;