Skip to content
🎄 Christmas Advent Calendar 2025 — Unwrap daily testing tips and surprises! View Calendar

Selenium: check if element exists

29-10-2019 Roy de Kleijn

Sometimes checking if an element exists on a page can be very useful. The code below demonstrates how to do that.

@Test
public void checkIfElementExists() {
	driver.get("http://www.github.com");

	if (driver.findElements(By.id("elementNotExists")).size() != 0) {
		System.out.println("Element exist");
	} else {
		System.out.println("Element doesn't exist");
	}
}

It returns a list of WebElements matching the locator and then it evaluates if the size is not equal to 0

Please be aware:

  1. If you use an implicitlyWait it can that longer if the element doesn't exists.
  2. The use of implicitlyWait is not the best. I highly recommend WebDriverWait.
Share:
Roy de Kleijn

Test Automation Expert

With over 15 years of experience in software testing and test automation, Roy helps teams improve their testing processes.

Want to learn more?

Check out our trainings and take your test automation skills to the next level.