WebDriver commands – Part 3 (findElement(s) Commands)

Now, we are going to  discuss about the two important methods defined in SearchContext interface are used to find web elements of web page. And those are :

  1. findElement (By by)
  2. findElements (By by)

Both the methods accept By class’ reference as a parameter to find the element.

FindElement

We can use any of the 8 methods defined in By class to find the element on the web page.

ByTypes

To understand each and every locating mechanism of locating element in detail, visit :  Locators in Selenium WebDriver (By strategy).

 

findElement command :

Usage : Used to locate the element on the web page using the given mechanism.

Syntax :  WebElement findElement(By by);

Return type : WebElement reference

Parameters : By reference (Any of the 8 methods)

Example :

WebElement byId = driver.findElement(By.id(“IdOfElement”));

WebElement byName = driver.findElement(By.name(“nameOfElement”));

WebElement byLinkText = driver.findElement(By.linkText(“link text”));

WebElement partialLinkText = driver.findElement(By.partialLinkText(“partial link text”));

WebElement partialLinkText = driver.findElement(By.tagName(“tagName”));

WebElement byClassName = driver.findElement(By.className(“classNameOfElement”));

WebElement byCssSelector = driver.findElement(By.cssSelector(“css selector expression”));

WebElement byXpath = driver.findElement(By.xpath(“xpath expression”));

If more than one elements are found within the current page using the given mechanism, findElement method returns the first occurrence of the element.


findElements command :

Usage : Used to locate all the element(s) on the web page using the given mechanism.

Syntax :  List<WebElement> findElements(By by);

Return type : List<WebElement> (A list of WebElements)

Parameters : By reference (Any of the 8 methods)

Example :

List<WebElement> listOfElements  = driver.findElements(By.name(“nameOfElement”));

List<WebElement> inputTagsList = driver.findElements(By.tagName(“input”));

If more than one elements are found within the current page using the given mechanism, findElements method returns the list containing all the WebElements.

If only one element is found using the given mechanism, findElements method returns the list containing the single WebElement.

If not a single element is found using the given mechanism, findElements method returns an empty list of WebElement.

Visit Difference between findElement and findElements in Selenium WebDriver.

Click here to know more about Browser Window Handling commands.

Hope it helps you!!

Cheers 🙂

Advertisements

#findelement, #findelements