From the name, you can guess the use of findElement and findElements. Yes. You are correct. If you want to locate a single element of the web page, then you need to use findElement method. In same way, for locating multiple element in a single method, then you need to user findElements. Let’s understand the difference between findElement and findElements.
findElement in Selenium:
In previous section, you may notice that WebDriver returns either something or nothing i.e. void. Here the return type of findElement / findElements is WebElement.
Let’s see the syntax and return type:
WebElement name = driver.findElement(By.id(“name”))
You can ask what is By?
By Ob = By,id(“Id of the element”);
By is a mechanism to locate an elements of the web page. findElements accept the By Object as Parameter / Argument and locate the element in web page. Below is the syntax of By Object.
WebElement wb = driver.findElement(Ob);
List<WebElement> elementName = driver.findElements(By.LocatorStrategy(“Locator Value”) );
|It returns the first most web element if there are multiple web elements found with the same locator||It returns a list of web elements|
|This will throws exception NoSuchElementException if there are no elements matching the locator strategy||It returns an empty list if there are no web elements matching the locator strategy|
|It will find only one web element||It will find a collection of elements whose match the locator strategy.
Form the above table, we have understood that findElement returns the first most web element if there are multiple web elements found with the same locator. But findElements returns a list of web elements. So in real scenario, if we are need to verify or work with more that one data, when we need to handle the data by using the findElements(). If we need to check only one variable like page tile, user name, status etc. we need to use findElement().
If there is no record found the the page then finfElement will return the NoSuchElementException. But findElements() will return empty list if there is no web element found.
Though findElements() return more than one web element, all web elements are indexed with a number and the index is starts from 0. Same way second element is indexed as 1 and so on.