As a part of Selenium Interview Questions series, in this post, we will learn differences between findElement() and findElements() methods in Selenium WebDriver.
WebDriver interface provides two methods to locate web element/s. Those are:-
- findElement(By by)
- findElements(By by)
Difference between findElement() and findElements() are below:-
- findElement() is used to find first web element on current page by provided locator mechanism such as id, xpath, css etc whereas findElements() is used to find all web elements on current page by provided locator mechanism such as id, xpath, css etc.
- findElement() will return only first web element even provided locator locates more than one web element. findElements() returns all matching web elements. findElement() method internally calls findElements() method itself and return first indexed web element.
- Return type of findElement() method is a WebElement whereas return type of findElements() method is a List<WebElement>.
- findElement() will throw NoSuchElementException if no matching element is found. findElements() will return an empty list if no matching element is found. This is the reason findElements() is a better way for checking non-presence of web element. Kindly concentrate on this point more. NoSuchElementException is thrown by findElement() not findElements().
WebElement element = driver.findElement(By.id(“someId”);
List<WebElement> allElements =driver.findElements(By.xpath(“someXpath”);
Where “driver” is a WebDriver reference.
There is another important points which I would like to cover here. It is not difference but common thing between methods. Its impact of Implicit Wait.
Both method findElement() and findElements() are affected by ‘Implicit wait’ times in force at the time of execution. If you do not set any impliict wait, findElement() and findElements() will poll only once and return the result. It means if element is found in first poll, findElement() will return the element otherwise NoSuchElementException . In case of findElements(), it will return a list of matching web elements or an empty list after first poll. Both method will not poll further.
But if you have set Implicit wait, both method will poll repeatedly. findElement() will poll for web element repeatedly till it finds web element or the timeout is reached. If it finds web element before timeout, it returns web element. If it could not find within timeout, it will throw NoSuchElementException exception.
findElements() will poll for web elements and return as soon as there are more than 0 items in the found collection before timeout. If it reaches timeout and finds no element, it will return an empty list.
If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.