How to Use Selenium to Find Element

This week Alex looks at Selenium Find Element and a checklist of tips of things to do when an element cannot be found.


What to do when an web element cannot be found? We all had to deal with situations when a test script cannot find an element using code as follows:

WebElement element = driver.findElement(locator);

If findElement() cannot find the element, a NoSuchElementException is generated.

The element is in the page. The locator of the element is correct as well. If findElement() does not work, what else can you do?


1. Use a Different Locator

If you used the element’s id as locator, try a CSS locator instead.

Or an XPATH locator.

2. Synchronize the code with the page

Explicit waits and expected conditions are great when the page loads slowly.

They will keep trying to find the element until the element is available and it has a specific state:

WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(locator));

Make sure that the expected condition matches the element’s status:

presenceOfElementLocated() – if the element is not visible

visibilityOfElementLocated() – if the element is visible

elementToBeClickable() – if the element is clickable

3. Is the element included in a frame?

If the element is in a frame, you need to switch the current driver’s context to the frame before trying to find it:

WebElement element = driver.findElement(locator);

Remember to switch back from the frame to the main page when you are done interacting with frame elements.

4. Use Javascript

If none of the previous tips works, you can try finding the element by Javascript:

String jsQuery = 
"function getElement()" +
"{var element = document.getElementById('id123'); return element; }; " +
"return getElement()";

WebElement element = (WebElement) jsExecutor.executeScript(jsQuery);


5. Reload the page

Sometimes, the element is just in an invalid state and nothing works.

You can reload the page and retry.

This worked for me in a number of occasions.

Have other tips for Selenium Find element?

Please share them in the comments below


About The Author

Alex SiminiucAlex lives in Vancouver, Canada. He has worked as a software tester since 2005. Alex teaches manual testers test automation with Selenium WebDriver and Java. Alex blogs on testing and automation at

About the Author

Ronan Healy

Hi everyone. I'm part of the EuroSTAR team. I'm here to help you engage with the EuroSTAR Huddle Community and get the best out of your membership. Together with software testing experts, we have a range of webinars and eBooks for you to enjoy and we have lots of opportunities for you to come together online. If you have any thoughts about the community, please get in contact with me.
Find out more about @ronan