Hero Background

Next-Gen App & Browser Testing Cloud

Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Next-Gen App & Browser Testing Cloud

What is a Web Element in Selenium Java?

In Selenium Java, a WebElement is an object that represents a single element on a web page, such as a button, link, text field, checkbox, image, or any other HTML node. WebElement is one of the core interfaces in the org.openqa.selenium package, and it is the handle you use to click, type, read text, and inspect the state of anything on the page during test automation.

Once you locate an element with findElement(), Selenium returns a WebElement object. From that point on, every interaction, from clicking a submit button to validating an error message, flows through the methods this interface exposes.

Understanding the WebElement Interface

WebElement is an interface, not a class, so you never instantiate it directly with new. At runtime, Selenium supplies a concrete implementation such as RemoteWebElement, and you always program against the WebElement contract. This design lets the same test code drive a local browser or a remote grid without any changes.

Each WebElement is tied to a specific node in the live DOM. If the page reloads or the framework re-renders that part of the DOM, the reference can become stale, which is why you locate elements as close as possible to the moment you interact with them.

  • Interaction: Perform actions such as clicking, typing, clearing fields, and submitting forms.
  • Element information: Read text, attribute values, CSS properties, tag names, and coordinates.
  • Element states: Check whether an element is displayed, enabled, or selected before acting on it.
  • Nested search: Call findElement on an existing WebElement to scope a search to its child nodes.

How to Locate a WebElement

Before you can act on a WebElement, you must find it. Selenium uses locators passed to findElement() through the By class. The eight standard locator strategies are ID, Name, Class Name, Tag Name, Link Text, Partial Link Text, CSS Selector, and XPath. Prefer ID because it is unique and fastest; fall back to a scoped CSS selector when no stable ID exists.

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class LocateElement {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.lambdatest.com/selenium-playground/");

        // Locate a single WebElement by its ID
        WebElement usernameField = driver.findElement(By.id("username"));

        // Locate using a CSS selector
        WebElement loginButton = driver.findElement(By.cssSelector("button[type='submit']"));

        driver.quit();
    }
}

Common WebElement Methods in Selenium Java

Once you hold a WebElement, these are the methods you will use most often:

  • click(): Clicks a button, link, checkbox, or radio button.
  • sendKeys(CharSequence...): Types text or key presses into an input field.
  • clear(): Empties a text field before entering new input.
  • getText(): Returns the visible inner text of the element.
  • getAttribute(String): Returns the value of an attribute such as value, href, or class.
  • isDisplayed(), isEnabled(), isSelected(): Return boolean states used in assertions and conditional logic.
  • getCssValue(String): Reads a computed CSS property such as color or font-size.
WebElement usernameField = driver.findElement(By.id("username"));
usernameField.clear();
usernameField.sendKeys("standard_user");

WebElement loginButton = driver.findElement(By.cssSelector("button[type='submit']"));

if (loginButton.isDisplayed() && loginButton.isEnabled()) {
    loginButton.click();
}

WebElement heading = driver.findElement(By.tagName("h1"));
System.out.println("Heading text: " + heading.getText());

findElement vs findElements

Both methods locate elements, but they behave differently, which matters when you handle lists, tables, or optional content. See our detailed comparison of findElement and findElements for more.

  • findElement(): Returns the first matching WebElement and throws NoSuchElementException if nothing matches.
  • findElements(): Returns a List<WebElement> of every match and returns an empty list, never an exception, when nothing matches.
  • Use findElements() with .isEmpty() to safely check whether an element exists without a try-catch block.
import java.util.List;

// Collect every product link and iterate over them
List<WebElement> links = driver.findElements(By.cssSelector(".product a"));
System.out.println("Found " + links.size() + " links");

for (WebElement link : links) {
    System.out.println(link.getText() + " -> " + link.getAttribute("href"));
}

Common Mistakes and Troubleshooting

  • StaleElementReferenceException: The DOM changed after you stored the reference. Re-locate the element immediately before interacting with it.
  • NoSuchElementException: The locator is wrong or the element has not loaded yet. Verify the selector and add an explicit WebDriverWait.
  • ElementNotInteractableException: The element is hidden or covered. Wait for visibility, scroll it into view, or close the overlapping overlay.
  • Using getText() for input values: getText() returns rendered text only. Use getAttribute("value") to read what a user typed into a field.
  • Relying on Thread.sleep(): Hard-coded waits make tests flaky and slow. Prefer explicit waits tied to a condition such as elementToBeClickable.

Testing WebElements Across Real Browsers and Devices

A WebElement can render and behave differently across browsers, versions, and screen sizes, so a locator that works in Chrome may fail on Safari or an older mobile browser. Running your Selenium Java suite on TestMu AI lets you validate the same WebElement interactions across 3000+ real browsers and operating systems in the cloud, without maintaining local infrastructure.

You keep your existing code and point the Selenium Java tests at a remote driver, then scale them in parallel across a Selenium automation grid. This surfaces element-level rendering and interaction issues early and speeds up feedback through cross browser testing.

Conclusion

A WebElement is the fundamental building block of Selenium Java automation, the object through which you inspect and drive every button, field, and link on a page. Master how to locate elements with the right locator, use the core methods effectively, and handle stale or missing elements gracefully, and your tests become far more reliable. Combine that discipline with cloud execution to confirm your WebElement interactions hold up across the browsers your users actually run.

Frequently Asked Questions

Is WebElement a class or an interface in Selenium Java?

WebElement is an interface in the org.openqa.selenium package. Selenium provides concrete implementations such as RemoteWebElement at runtime, so you always program against the WebElement interface rather than creating it directly with the new keyword.

What is the difference between findElement and findElements?

findElement returns a single WebElement and throws NoSuchElementException when nothing matches. findElements returns a List of WebElements and returns an empty list, not an exception, when no element matches the locator, making it safer for existence checks.

How do I get the text of a WebElement in Selenium Java?

Call getText() on the located WebElement to read its visible inner text. For hidden text or attribute values such as value or href, use getAttribute() instead, since getText() only returns text that is actually rendered on the page.

Why do I get a StaleElementReferenceException?

A stale element error occurs when the DOM is refreshed or re-rendered after you stored a WebElement reference. Re-locate the element just before interacting with it, and use explicit waits so the reference stays attached to the live DOM.

Can a WebElement be used to find child elements?

Yes. You can call findElement or findElements on an existing WebElement to scope the search to its descendants. This is useful for locating a specific row inside a table or an item inside a particular container without matching similar elements elsewhere.

Which locator is best for finding a WebElement?

ID is the fastest and most reliable locator because it is usually unique. When no stable ID exists, a well-scoped CSS selector is the next best choice, with XPath reserved for cases that need text matching or complex DOM traversal.

Related Questions

Test Your Website on 3000+ Browsers

Get 100 minutes of automation test minutes FREE!!

Test Now...

KaneAI - Testing Assistant

World’s first AI-Native E2E testing agent.

...

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests