getLocation() method in Selenium Java

The getLocation() method is used to find the location of an element on the webpage. This post will discuss the getLocation() method of the WebElement interface in detail.

  • Method declaration – Point getLocation();
  • What does it do? – It will get the location of the top left-hand corner of the specified WebElement.
  • What does it return? – It will return a Point object denoting the location of the element. We can use the getX() or the getY() method provided by the Point class to get the x and y coordinates of the element.

Note: The location of any element on the webpage is calculated by considering the top left-hand corner of the webpage to be at (0,0) coordinates.

Top left-hand corner of webpage

Now, let’s try to get the location of the 1st text field on this page using the getLocation() method. getLocation() will get the top left-hand point location of the specified web element.

getLocation() returns the top left-hand corner

As getLocation() returns a Point class object, we can use the getX() and getY() to get the x and y coordinates of the web element.

import org.openqa.selenium.By;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;

public class CodekruTest {

	@Test
	public void test() {

		// pass the path of the chromedriver location in the second argument
		System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
		WebDriver driver = new ChromeDriver();

		// opening the url
		driver.get("https://testkru.com/Elements/TextFields");

		WebElement element = driver.findElement(By.id("firstName"));

		Point point = element.getLocation();
		System.out.println("x location: " + point.getX());
		System.out.println("y location: " + point.getY());

	}
}

Output –

x location: 532
y location: 427

Similarly, we can find the location of any element on the webpage.

What if we use the getLocation() method on a null WebElement?

We will get a NullPointerException as illustrated by the below program.

public class CodekruTest {

	@Test
	public void test() {

		// pass the path of the chromedriver location in the second argument
		System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
		WebDriver driver = new ChromeDriver();

		// opening the url
		driver.get("https://testkru.com/Elements/TextFields");

		WebElement element = null;
		Point point = element.getLocation();

	}
}

Output –

java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebElement.getLocation()" because "element" is null

Please visit this link to learn more about WebElement and its methods.

We hope that you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at [email protected]

Liked the article? Share this on

Leave a Comment

Your email address will not be published.