Explore Courses Blog Tutorials Interview Questions
0 votes
in DevOps and Agile by (19.7k points)

I want to check if an element exists in Selenium, and if it does, assign it to a name.

Right now I have something that looks like this:

IWebElement size9 = driver.FindElement(By.CssSelector("a[data-value*='09.0']"));

However, when that element that has the value of 9 does not exist, it returns an error. Is there a way I can check to see if it exists, or something of that sort?

1 Answer

0 votes
by (62.9k points)

There are several options. I recommend these.

1. Create a method or web driver extension.

public static IWebElement FindElementIfExists(this IWebDriver driver, By by)


    var elements = driver.FindElements(by);

    return (elements.Count >=1) ? elements.First() : null;


// Usage

var element = driver.FindElementIfExists(By.CssSelector("a[data-value*='09.0']"));

2. Count the element, get it if there are 1 or more elements.

 By by = By.CssSelector("a[data-value*='09.0']");

var element = driver.FindElements(by).Count >= 1 ? driver.FindElement(by) : null;

Then you can check if(element != null) { ... } 

If you are interested to learn Selenium on a much deeper level and want to become a professional in the testing domain, check out Intellipaat’s automation testing certification!

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.4k questions

32.5k answers


108k users

Browse Categories