Selenium WebDriver provides two methods for finding web elements on a webpage – driver.findElement() and driver.findElements(). In this post, we will study the difference between the two and also see where to use them effectively.
Difference between driver.findElement and driver.findElements
|Definition||driver.findElements() is used to find a List of webElements matching the locator passed as a parameter.||driver.findElements() is used to find a List of webElements matching the locator passed as parameter.|
|Syntax||WebElement element = driver.findElement(By locator);||List<WebElement> elements = driver.findElements(By locator);|
|For multiple matches||In case the same locator matches multiple webElements then findElement method returns the first web element found.||In case the same locator matches multiple web elements then findElements method returns the first web element found.|
|If no element is found||In case the locator passed to findElement() method leads to no element then NoSuchElementException is thrown.||In case the locator passed to findElements() method leads to no element then a List of 0 size is returned instead of an exception.|
Please note that because of the fact that in case no element is found driver.findElements() return a list of size 0 (unlike findElement() that throws an exception), it is generally used to check for the presence of an element.
We can just check the size of the list returned by findElements() method and if it is non-zero, we can interact with the first element of the list using the 0 index.
Check out our complete step-by-step selenium tutorial here.
Kuldeep is the founder and lead author of ArtOfTesting. He is skilled in test automation, performance testing, big data, and CI-CD. He brings his decade of experience to his current role where he is dedicated to educating the QA professionals. You can connect with him on LinkedIn.