Different Ways of Locating Elements in WebDriverThere are various elements to interact within Selenium WebDriver. Elements like select, click, type or verify needs to be located first to initiate any interaction with them. There are different ways of locating such elements supported by WebDriver on html pages. I have taken examples of CSS and XPath to locate elements. However, there are different methods that can be used to locate elements.

Using Id

The Id of an element represents the element’s identifier, which is considered the most preferred and efficient way to retrieve or locate an element. In addition, it can also be used as a selector while using CSS to style a document. However, ids are generated automatically, which makes it complex to retrieve an element or at times they are not considered for HTML elements.

You can use the following command to locate an element based on Ids.

 <div id=“name”>

driver.findElement(By.id(“name”));

Using Class Name

The className property defines the class name of an element, where the ‘Class’ refers to the attribute on the DOM element related to a CSS property.

The following command can be used to locate an element based on Class Name.

 <span class=“even”>

driver.findElement(By.className(“even”));

Using Tag Name

The tagName property sets the tag name of a DOM element, which is always in UPPERCASE in html.

To locate an element based on Tag Name, use the following command.

<img src=“./logo.png”>

driver.findElement(By.tagName(“img”));

Using Name

The name attribute specifies the name of an input element.

You can use the following command to locate the input element with matching name attribute.

<input name=“color” value=”blue”>

driver.findElement(By.name(“color”));

Using Link Text

The link text is the visible part and returns you to the specified address by clicking it.

To locate the link element with matching visible text, use the following command.

<a href=http://xyz/>Software Testing</a>

driver.findElement(By.linkText(“Software Testing”));

Using Partial Link Text

Partial link text is preferred over link text when the link text is big.

The following command can be used to locate a link element with partial matching visible text.

<a href=”http://www.xyz.com/”>Software Testing</a>

driver.findElement(By.partialLinkText(“Testing”));

You may also like: How to Add, Retrieve, and Delete Cookies in WebDriver?