To check if an element exists in Selenium Java, the safest and most common method is to use the findElements()
method. This method returns a list of matching elements—if the list size is greater than zero, the element exists; if the list is empty, the element does not exist. This approach avoids exceptions and is more efficient than using findElement()
, which throws a NoSuchElementException
if the element is not found.
Example: Check If Element Exists Using findElements()
Method
package org.example; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.List; public class Main { public static void main(String[] args) { WebDriver driver = new ChromeDriver(); driver.get("https://www.google.com"); List<WebElement> elements = driver.findElements(By.id("elementId")); if (elements.size() > 0) { System.out.println("Element exists!"); } else { System.out.println("Element does not exist."); } driver.quit(); } }
- Replace
By.id("elementId")
with the desired locator for your element.
Alternative: Using Try-Catch with findElement()
Method
You can also use findElement()
in a try-catch block, but this is less preferable due to exception handling overhead:
import org.openqa.selenium.NoSuchElementException; boolean exists; try { driver.findElement(By.id("elementId")); exists = true; } catch (NoSuchElementException e) { exists = false; }
Summary Table
Method | Behavior if Element Not Found | Exception Safe | Example Code |
---|---|---|---|
findElements() | Returns empty list | Yes | driver.findElements(By.id("id")) |
findElement() | Throws NoSuchElementException | No | driver.findElement(By.id("id")) |
Recommendation: Use findElements()
and check the list size, as it is the most robust and readable way to check for the existence of an element in Selenium Java.