WebElement in Selenium

โšก Smart Summary

WebElement in Selenium represents every form control as a programmable object, enabling testers to interact with text fields, checkboxes, radio buttons, and submit elements using findElement, sendKeys, click, clear, and submit methods through Java code examples.

  • ๐Ÿงฉ Locator Precision: Identify form elements by id, name, xpath, or CSS selector through findElement() to ensure stable interaction with the DOM.
  • โœ๏ธ Input Handling: Send editable text into fields using sendKeys() without overwriting existing values during automated execution.
  • ๐Ÿงน Field Reset: Clear input boxes through the clear() method before re-entering data, preventing residual values in later assertions.
  • ๐Ÿ–ฑ๏ธ Button Interaction: Trigger sign-in or navigation actions through the click() method on the matching WebElement reference.
  • ๐Ÿ“จ Form Submission: Use submit() on any element within a form so WebDriver automatically dispatches its parent form submit handler.
  • ๐Ÿ›ก๏ธ Stability Tip: Add implicit or explicit waits before findElement() calls to prevent NoSuchElementException on dynamically loaded pages.

WebElement in Selenium

WebElement in Selenium

Forms are the fundamental web elements that capture information from website visitors. Web forms include different GUI controls such as text boxes, password fields, checkboxes, radio buttons, dropdowns, and file inputs.

This tutorial explains how to access each form element using Selenium WebDriver with Java. Selenium encapsulates every form element as an object of WebElement. It provides an API to locate elements and act on them, including entering text, clicking buttons, and submitting forms. The sections below cover the methods available for each form element.

Introduction To WebElement FindElement,FindElements

Introduction to WebElement, findElement(), findElements()

Selenium WebDriver represents a simple form element as an object of WebElement.

WebDriver identifies form elements using different properties of the web element, including ID, Name, Class, XPath, Tagname, CSS selectors, and link text.

WebDriver provides the following two WebElement methods to find elements:

  • findElement() โ€“ finds a single web element and returns it as a WebElement Selenium object.
  • findElements() โ€“ returns a list of WebElement objects matching the locator criteria.

The example below shows how to retrieve a single element, a text field on a web page, as a WebElement object using the findElement() method. The findElements() method for finding multiple elements is covered in subsequent tutorials.

Step 1) Import the package required to create WebElement objects.

Step 2) Call the findElement() method available on the WebDriver class to retrieve a WebElement object, as shown below.

Selenium Input Text

Input boxes refer to either of these two types:

  1. Text Fields โ€“ Selenium input text boxes that accept typed values and display them exactly as entered.
  2. Password Fields โ€“ text boxes that accept typed values but mask them as a series of special characters (commonly dots or asterisks) to hide sensitive input.

    Selenium Input Text

Locators

The findElement() method takes one parameter, which is a locator that points to the element. Different locators, including By.id(), By.name(), By.xpath(), and By.cssSelector(), find elements on the page using their properties such as id, name, or path.

You can use plugins like FirePath to obtain the id, xpath, and other locator values for elements.

Using the example site https://demo.guru99.com/test/login.html, the code below locates the “Email Address” text field using the id locator and the “Password” field using the name locator.

Locators

  1. Email text field is located by id.
  2. Password field is located by name.

sendkeys in Selenium

sendKeys() in Selenium is a method used to enter editable content in text and password fields during test execution. These fields are identified through locators such as name, class, and id. The method is available on the WebElement object. Unlike the type method, sendKeys() does not replace the existing text in a text box.

How to Enter Text in Selenium

To enter text into text fields and password fields, sendKeys() is the method available on the WebElement in Selenium.

Using the same example of https://demo.guru99.com/test/login.html, the snippet below locates the text field and password field and enters text in Selenium.

Text in Selenium

  1. Find the “Email Address” text field using the id locator.
  2. Find the “Password” field using the name locator.
  3. Enter text into the “Email Address” using the Selenium sendKeys method.
  4. Enter a password into the “Password” field using the sendKeys() method.

Deleting Values in Input Boxes

The clear() method deletes the text inside an input box. This method does not need a parameter. The snippet below clears the text from the Email or Password fields.

Deleting Values in Input Boxes

Selenium Click Buttons

The Selenium click button is accessed using the click() method.

In the example above

  1. Find the button to Sign in.
  2. Click the “Sign-in” button on the login page of the site to authenticate.

Selenium Click Buttons

Selenium Submit Buttons

Submit buttons send the entire form to the server. You can either call the click() method on the WebElement, as shown above, or use the submit() method on any element in the form or on the submit button itself.

Selenium Submit Buttons

When submit() is used, WebDriver looks up the DOM to identify the form that the element belongs to and then triggers its submit function.

Complete Code

Here is the complete working code.

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

public class Form {
    public static void main(String[] args) {

        // declaration and instantiation of objects/variables
        System.setProperty("webdriver.chrome.driver", "G:\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();

        String baseUrl = "https://demo.guru99.com/test/login.html";
        driver.get(baseUrl);

        // Get the WebElement corresponding to the Email Address(TextField)
        WebElement email = driver.findElement(By.id("email"));

        // Get the WebElement corresponding to the Password Field
        WebElement password = driver.findElement(By.name("passwd"));

        email.sendKeys("abcd@gmail.com");
        password.sendKeys("abcdefghlkjl");
        System.out.println("Text Field Set");

        // Deleting values in the text box
        email.clear();
        password.clear();
        System.out.println("Text Field Cleared");

        // Find the submit button
        WebElement login = driver.findElement(By.id("SubmitLogin"));

        // Using click method to submit form
        email.sendKeys("abcd@gmail.com");
        password.sendKeys("abcdefghlkjl");
        login.click();
        System.out.println("Login Done with Click");

        // Using submit method to submit the form. Submit used on password field
        driver.get(baseUrl);
        driver.findElement(By.id("email")).sendKeys("abcd@gmail.com");
        driver.findElement(By.name("passwd")).sendKeys("abcdefghlkjl");
        driver.findElement(By.id("SubmitLogin")).submit();
        System.out.println("Login Done with Submit");

        // driver.close();
    }
}

Troubleshooting

If you encounter NoSuchElementException() while finding elements, the element is not present in the page at the moment WebDriver accessed it.

  1. Recheck your locator using FirePath or the Inspect Element option in Chrome.
  2. Check whether the value used in the code differs from the current value of the element seen in FirePath.
  3. Some attributes are dynamic for certain elements. If a value changes dynamically, switch to By.xpath() or By.cssSelector(), which are more reliable but slightly more complex.
  4. Sometimes the issue is a wait condition; WebDriver may execute the code before the page finishes loading.
  5. Add a wait before findElement() using implicit or explicit waits.

Summary

  • The table below summarizes the commands to access each type of element discussed above.
Element Command Description
Input Box sendKeys() Used to enter values into text boxes.
clear() Used to clear text boxes of their current value.
Links click() Used to click on the link and wait for the page load to complete before proceeding to the next command.
Submit Button submit() Used to submit the form by trigging the parent form’s submit handler.
  • WebDriver allows selection of more than one option in a multiple SELECT element.
  • You can use the submit() method on any element within the form. WebDriver automatically triggers the submit function of the form that the element belongs to.

FAQs

findElement() returns the first matching WebElement and throws NoSuchElementException when none exists. findElements() returns a list of matching WebElements and returns an empty list when no element matches the locator.

A WebElement is a Selenium wrapper that exposes automation methods such as sendKeys, click, and clear. An HTML element is the underlying DOM node. WebDriver locates the DOM node and returns a WebElement reference for interaction.

Yes. AI-assisted tools analyze the DOM and propose stable locators using id, name, relative xpath, or CSS selectors. They reduce locator brittleness by detecting unique attribute combinations and suggesting fallbacks when an attribute changes.

Yes. AI-driven self-healing locators automatically re-bind a WebElement when an attribute changes. This reduces flaky failures, lowers maintenance effort, and keeps Selenium suites stable across frequent UI updates in agile delivery cycles.

Common WebElement exceptions include StaleElementReferenceException, ElementNotInteractableException, ElementClickInterceptedException, InvalidElementStateException, and TimeoutException. Each indicates a different DOM, visibility, or synchronization issue that should be handled with waits or refreshed element references.

Summarize this post with: