We use cookies to analyze site traffic and show personalized ads. You can accept all cookies or decline personalized advertising.
Learn more in our Privacy Policy.
Retrieve the dimensions and coordinates of an element for layout validation.
When you need to verify where an element is on the page and how big it is, Selenium gives you geometry data through getRect().
getRect() returns a Rectangle object containing X, Y coordinates and width, height dimensions.
getLocation() and getSize() still work, but getRect() combines both and is cleaner.Resize the browser window or scroll to see the rect values update!
1234567891011121314WebElement box = driver.findElement(By.id("target-box"));
Rectangle rect = box.getRect();
System.out.println("X: " + rect.getX());
System.out.println("Y: " + rect.getY());
System.out.println("Width: " + rect.getWidth());
System.out.println("Height: " + rect.getHeight());
// Sanity check: Is it visible with non-zero size?
if (rect.getWidth() > 0 && rect.getHeight() > 0) {
System.out.println("Element has valid dimensions.");
}
driver.quit();Use getRect() instead of combining getLocation() and getSize().
Use small pixel tolerance for cross-browser differences.
If element is tiny/off-screen, that's why interactions fail.