[ XF9 ]

Check if element exists with selenium

Posted on in C#.

Selenium offers no ElementExists() or HasChildNodes() to check whether an element exists and/or has child nodes. So if you want to use one of these function you are pretty much out of luck.

You could query for the element directly and use an ugly try/catch thingy:

try {
   driver.FindElement(By.id("ElementIdToFind"));
   // element is present
} catch (NoSuchElementException e) {
   // element isn't present
}

A much better way is to use FindElements and Count them ;)

var elements = driver.FindElements(By.id("ElementIdToFind"));
if(elements.Count > 0)
   // element is present
else
   // element is not present

And to count child nodes:

var nodes = driver.FindElements(By.id("ElementIdToFind")).findElements(By.xpath("*")).Count;

Write a reply or comment

Your email address will not be published.