# Among id, name, xpath and css, which locator should be used?

JavascriptWeb Development

Each of the locators has some significance. If the page contains unique

attribute values, we should use them first. However if there are no unique elements, we should use css selector as it is more effective in terms of speed.

Css also has a drawback that we cannot traverse from child to parent node which means we cannot travel backward. But xpath allows this feature. Xpath is the most common locator in Selenium and performs traversal through DOM elements and attributes to identify an object.

An xpath is represented by two ways namely ‘/ ‘and ‘// ‘. A forward single slash means absolute path. Here xpath traverses direct from parent to child in DOM. Thus in absolute xpath we have to travel from the root node to the target.

Syntax −

driver.findElement(By.xpath("/html/body/div/input")).

A double forward ‘// ‘slash means relative path. Here xpath finds the matching element in every corner of DOM. It doesn't have a particular beginning point.

Syntax −

driver.findElement(By.xpath("//input[@name=’Tutorial’]")).

It is always recommended to use relative xpath rather than absolute xpath. In absolute xpath, we need to specify from the root to the desired element so if any of the attributes and its value get changed in between, then our xpath will no longer be correct.

## Example

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class TextMatch {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",    "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = " https://www.tutorialspoint.com/questions/index.php";
driver.get(url);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//identifying element with xpath
driver.findElement(By.xpath("//input[@class=’gsc-input’]")).click();
driver.close();
}
}
Published on 10-Jun-2020 13:04:03