SearchContext interface 

SearchContext is the interface that has been designed to find elements in the DOM using a locator mechanism. SearchContext has two public methods:

  • findElementThis identifies all matching elements based on a locator mechanism but always returns the first matching web element.
  • findElements: This returns a list of WebElements that match the locator.

When Selenium returns a WebElement, it does not return an object of the WebElement, since the WebElement is an interface. Rather, it returns an object of RemoteWebElement, which is the implementation class of the WebElement interface.

What if the locator mechanism does not return any elements? In this case, findElement will always throw a NoSuchElementException. The findElements method, on the other hand, will not throw a No SuchElementException. It returns an empty list. 

Always use findElements when unsure about the existence of a WebElement based on some locator mechanism. This is the best practice to avoid NoSuchElementException at runtime. It is very likely you'll get this exception while using the  By.tagName static method, which we will see later.