WebElement Interface
The WebElement interface represents a single HTML element on a web page and provides all operations needed to interact with and validate UI elements. While WebDriver controls the browser, WebElement controls the elements inside the page.
1. What Is the WebElement Interface
Definition:
A WebElement is an object that represents a DOM element (input, button, link, dropdown, etc.) located by Selenium using a locator strategy.
In Selenium:
- WebDriver finds elements
- WebElement interacts with elements
- WebDriver → finds
- WebElement → acts
2. How WebElement Is Created
A WebElement is obtained using WebDriver’s locating methods:
findElement(By locator)→ returns one WebElementfindElements(By locator)→ returnsList<WebElement>
Until an element is found, no WebElement exists.
3. Responsibilities of WebElement
The WebElement interface allows you to:
- Perform actions (click, type)
- Read values (text, attributes)
- Validate state (visible, enabled, selected)
- Submit forms
- Traverse the DOM context (relative searches)
It does not:
- Navigate pages
- Manage windows
- Handle alerts
- Control browser lifecycle
4. Core WebElement Methods (Categorized)
4.1 Interaction Methods
click()→ clicks the elementsendKeys(String)→ types into input fieldsclear()→ clears text fieldssubmit()→ submits a form (rarely used now)
Used for: user actions.
4.2 Text & Attribute Methods
getText()→ visible text of elementgetAttribute(String)→ value of an attributegetCssValue(String)→ CSS property value
Used for: validations and assertions.
4.3 State Validation Methods
isDisplayed()→ visibility checkisEnabled()→ enabled/disabled stateisSelected()→ checkbox/radio selection state
Used for: conditional logic and assertions.
4.4 Size & Location (Advanced)
getSize()→ element dimensionsgetLocation()→ element positiongetRect()→ size + location combined
Used for: layout/debugging (not common in functional tests).
5. WebDriver vs WebElement (Clear Difference)
| Aspect | WebDriver | WebElement |
|---|---|---|
| Scope | Browser | Single element |
| Finds elements | ✅ Yes | ❌ No |
| Click/type | ❌ No | ✅ Yes |
| Navigation | ✅ Yes | ❌ No |
| Quantity | One per session | Many per page |
Rule: WebDriver locates; WebElement operates.
6. WebElement Is Dynamic (Very Important)
WebElement references are not permanent.
When the DOM changes (page reload, AJAX update):
- The old WebElement becomes invalid
- Using it throws
StaleElementReferenceException
Implication: Elements should be re-located after DOM changes.
7. Synchronization with WebElement
WebElement methods:
- Do not wait automatically
- Assume the element is ready
Best practice:
- Ensure presence/visibility/clickability before interaction
- Use explicit waits around WebElement usage
Ignoring this causes flaky tests.
8. WebElement in Page Object Model (POM)
In real frameworks:
- WebElements are defined in page classes
- Actions are wrapped in page methods
- Tests never call
findElement()directly
Why:
- Better readability
- Centralized locator management
- Lower maintenance
9. Common Beginner Mistakes
- Storing WebElement as static
- Reusing WebElement after page refresh
- Using WebElement without waits
- Performing assertions inside page classes
- Mixing locators in test classes
10. Interview Perspective
Short Answer:
The WebElement interface represents an HTML element and provides methods to interact with it, such as click, sendKeys, and getText.
Real-Time Answer:
In Selenium, WebElement represents a DOM element found by WebDriver. It provides APIs for interaction, state validation, and data retrieval. WebDriver controls the browser, while WebElement controls individual elements.
11. Key Takeaway
- WebElement is the core UI interaction interface
- It represents one element at a time
- It is state-sensitive and DOM-dependent
- Proper waits and re-location are essential
Mastering WebElement usage is the key to writing stable and maintainable Selenium tests.
12. WebElement Examples (Quick Reference)
1. Creating a WebElement Object
WebElement username =
driver.findElement(By.id("username"));
Key Point: WebElement represents one UI element and is returned by findElement().
2. Typing Text – sendKeys()
WebElement input = driver.findElement(By.name("email"));
input.sendKeys("test@example.com");
3. Clicking an Element – click()
WebElement loginBtn = driver.findElement(By.id("login"));
loginBtn.click();
4. Clearing Text Field – clear()
WebElement search = driver.findElement(By.id("search"));
search.clear();
search.sendKeys("Selenium");
5. Getting Visible Text – getText()
WebElement heading = driver.findElement(By.tagName("h1"));
System.out.println(heading.getText());
Interview Favorite: Works only on visible text.
6. Getting Attribute Value – getAttribute()
WebElement input = driver.findElement(By.id("email"));
System.out.println(input.getAttribute("value"));
7. Getting CSS Property – getCssValue()
WebElement button = driver.findElement(By.id("submit"));
System.out.println(button.getCssValue("color"));
8. Check if Element Is Displayed – isDisplayed()
WebElement logo = driver.findElement(By.id("logo"));
System.out.println(logo.isDisplayed());
9. Check if Element Is Enabled – isEnabled()
WebElement submit = driver.findElement(By.id("submit"));
System.out.println(submit.isEnabled());
10. Check if Element Is Selected – isSelected()
WebElement checkbox = driver.findElement(By.id("agree"));
System.out.println(checkbox.isSelected());
11. Submitting a Form – submit()
WebElement form = driver.findElement(By.id("loginForm"));
form.submit();
Note: Works only for form elements.
12. Getting Tag Name – getTagName()
WebElement element = driver.findElement(By.id("submit"));
System.out.println(element.getTagName());
13. Getting Element Size – getSize()
Dimension size = element.getSize();
System.out.println(size.getHeight());
System.out.println(size.getWidth());
14. Getting Element Location – getLocation()
Point point = element.getLocation();
System.out.println(point.getX());
System.out.println(point.getY());
15. Finding Child Elements (Chaining)
WebElement table = driver.findElement(By.id("users"));
List<WebElement> rows =
table.findElements(By.tagName("tr"));
System.out.println(rows.size());
16. findElements() on WebElement
WebElement menu = driver.findElement(By.id("menu"));
List<WebElement> items =
menu.findElements(By.tagName("li"));
17. Clicking Using JavaScript (When click() Fails)
WebElement btn = driver.findElement(By.id("submit"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", btn);
18. Sending Keys Using JavaScript
js.executeScript(
"arguments[0].value='admin';", input);
19. Highlighting Element (Debugging)
js.executeScript(
"arguments[0].style.border='3px solid red'", element);
20. Handling Stale Element Reference
WebElement btn = driver.findElement(By.id("save"));
driver.navigate().refresh();
// btn.click(); // ❌ StaleElementReferenceException
btn = driver.findElement(By.id("save")); // re-locate
btn.click();
21. WebElement with Explicit Wait (Best Practice)
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement loginBtn =
wait.until(ExpectedConditions.elementToBeClickable(By.id("login")));
loginBtn.click();
22. Loop Through Multiple WebElements
List<WebElement> links =
driver.findElements(By.tagName("a"));
for (WebElement link : links) {
System.out.println(link.getText());
}
23. WebElement in Page Object Model (POM)
@FindBy(id = "username")
WebElement username;
public void enterUsername(String name) {
username.sendKeys(name);
}
24. ❌ Common Interview Mistake
WebElement el = driver.findElement(By.id("x"));
el.getText("abc"); // ❌ invalid
Correct:
el.getText(); // ✅
25. WebElement vs WebDriver (Interview)
driver.findElement(); // finds elements
element.click(); // performs action
Difference:
- WebDriver → browser-level control
- WebElement → element-level control
26. WebElement Interface Hierarchy (Interview)
SearchContext
↑
WebElement
27. WebElement State Validation Example
Assert.assertTrue(loginBtn.isDisplayed());
Assert.assertTrue(loginBtn.isEnabled());
28. Real-World Login Example
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.id("password")).sendKeys("secret");
driver.findElement(By.id("login")).click();
29. Avoid Hard Sleeps (WebElement Stability)
// ❌ Thread.sleep(5000);
// ✅ use wait
wait.until(ExpectedConditions.visibilityOf(element));
30. Interview Summary – WebElement Interface
WebElement element = driver.findElement(By.locator);
Key Methods:
- click(), sendKeys(), clear()
- getText(), getAttribute()
- isDisplayed(), isEnabled(), isSelected()
- findElement() / findElements()