0
# Element Interaction
1
2
The WebElement interface provides comprehensive functionality for interacting with HTML elements, including clicking, typing, querying properties, and taking screenshots.
3
4
## Capabilities
5
6
### WebElement Interface
7
8
Core interface for HTML element interaction extending SearchContext and TakesScreenshot.
9
10
```java { .api }
11
/**
12
* WebElement interface for HTML element interaction
13
* Extends SearchContext for finding child elements and TakesScreenshot for element screenshots
14
*/
15
interface WebElement extends SearchContext, TakesScreenshot {
16
/**
17
* Click the element
18
*/
19
void click();
20
21
/**
22
* Submit a form containing this element
23
*/
24
void submit();
25
26
/**
27
* Type text into the element (usually input fields)
28
* @param keysToSend - Text and special keys to send
29
*/
30
void sendKeys(CharSequence... keysToSend);
31
32
/**
33
* Clear the content of the element (input fields and text areas)
34
*/
35
void clear();
36
37
/**
38
* Get the HTML tag name of the element
39
* @return Tag name in lowercase (e.g., "input", "div", "span")
40
*/
41
String getTagName();
42
43
/**
44
* Get DOM attribute value
45
* @param name - Attribute name
46
* @return Attribute value or null if not present
47
*/
48
String getDomAttribute(String name);
49
50
/**
51
* Get DOM property value
52
* @param name - Property name
53
* @return Property value or null if not present
54
*/
55
String getDomProperty(String name);
56
57
/**
58
* Get attribute value (legacy method, use getDomAttribute for new code)
59
* @param name - Attribute name
60
* @return Attribute value or null if not present
61
*/
62
String getAttribute(String name);
63
64
/**
65
* Get ARIA role of the element
66
* @return ARIA role or null if not present
67
*/
68
String getAriaRole();
69
70
/**
71
* Get accessible name of the element
72
* @return Accessible name or null if not present
73
*/
74
String getAccessibleName();
75
76
/**
77
* Check if the element is selected (checkboxes, radio buttons, options)
78
* @return true if selected, false otherwise
79
*/
80
boolean isSelected();
81
82
/**
83
* Check if the element is enabled for interaction
84
* @return true if enabled, false if disabled
85
*/
86
boolean isEnabled();
87
88
/**
89
* Check if the element is visible on the page
90
* @return true if displayed, false if hidden
91
*/
92
boolean isDisplayed();
93
94
/**
95
* Get the visible text content of the element
96
* @return Text content as seen by the user
97
*/
98
String getText();
99
100
/**
101
* Get computed CSS property value
102
* @param propertyName - CSS property name (e.g., "color", "font-size")
103
* @return Computed CSS value
104
*/
105
String getCssValue(String propertyName);
106
107
/**
108
* Get element position relative to top-left of page
109
* @return Point with x,y coordinates
110
*/
111
Point getLocation();
112
113
/**
114
* Get element dimensions
115
* @return Dimension with width and height
116
*/
117
Dimension getSize();
118
119
/**
120
* Get element position and dimensions combined
121
* @return Rectangle with position and size
122
*/
123
Rectangle getRect();
124
}
125
```
126
127
**Usage Examples:**
128
129
```java
130
import org.openqa.selenium.WebDriver;
131
import org.openqa.selenium.WebElement;
132
import org.openqa.selenium.By;
133
import org.openqa.selenium.Keys;
134
import org.openqa.selenium.chrome.ChromeDriver;
135
136
WebDriver driver = new ChromeDriver();
137
138
try {
139
driver.get("https://example.com/form");
140
141
// Find and interact with input elements
142
WebElement usernameField = driver.findElement(By.id("username"));
143
WebElement passwordField = driver.findElement(By.id("password"));
144
WebElement submitButton = driver.findElement(By.xpath("//button[@type='submit']"));
145
146
// Type into input fields
147
usernameField.sendKeys("testuser");
148
passwordField.sendKeys("password123");
149
150
// Clear field and retype
151
usernameField.clear();
152
usernameField.sendKeys("newuser");
153
154
// Use special keys
155
usernameField.sendKeys(Keys.CONTROL, "a"); // Select all
156
usernameField.sendKeys("replacedtext");
157
158
// Check element properties
159
System.out.println("Tag name: " + usernameField.getTagName()); // "input"
160
System.out.println("Type attribute: " + usernameField.getDomAttribute("type")); // "text"
161
System.out.println("Value property: " + usernameField.getDomProperty("value"));
162
System.out.println("Placeholder: " + usernameField.getAttribute("placeholder"));
163
164
// Check element state
165
if (submitButton.isEnabled() && submitButton.isDisplayed()) {
166
submitButton.click();
167
}
168
169
// Work with checkboxes and radio buttons
170
WebElement checkbox = driver.findElement(By.id("terms"));
171
if (!checkbox.isSelected()) {
172
checkbox.click();
173
}
174
175
// Get element information
176
Rectangle rect = usernameField.getRect();
177
System.out.println("Element position: " + rect.getX() + "," + rect.getY());
178
System.out.println("Element size: " + rect.getWidth() + "x" + rect.getHeight());
179
180
// Get CSS properties
181
String color = usernameField.getCssValue("color");
182
String fontSize = usernameField.getCssValue("font-size");
183
184
// Get accessible information
185
String ariaRole = submitButton.getAriaRole();
186
String accessibleName = submitButton.getAccessibleName();
187
188
} finally {
189
driver.quit();
190
}
191
```
192
193
### SearchContext Interface
194
195
Element finding interface implemented by both WebDriver and WebElement for locating child elements.
196
197
```java { .api }
198
/**
199
* SearchContext interface for element finding
200
* Implemented by WebDriver (searches entire page) and WebElement (searches within element)
201
*/
202
interface SearchContext {
203
/**
204
* Find the first element matching the given locator
205
* @param by - Element locator strategy
206
* @return First matching WebElement
207
* @throws NoSuchElementException if no element found
208
*/
209
WebElement findElement(By by);
210
211
/**
212
* Find all elements matching the given locator
213
* @param by - Element locator strategy
214
* @return List of matching WebElements (empty list if none found)
215
*/
216
List<WebElement> findElements(By by);
217
}
218
```
219
220
**Usage Examples:**
221
222
```java
223
// Find elements from driver (entire page)
224
WebElement form = driver.findElement(By.id("loginForm"));
225
List<WebElement> allInputs = driver.findElements(By.tagName("input"));
226
227
// Find child elements within a parent element
228
WebElement navigation = driver.findElement(By.className("navbar"));
229
List<WebElement> navLinks = navigation.findElements(By.tagName("a"));
230
WebElement homeLink = navigation.findElement(By.linkText("Home"));
231
232
// Chain element searches
233
WebElement table = driver.findElement(By.id("dataTable"));
234
WebElement firstRow = table.findElement(By.xpath(".//tr[1]"));
235
List<WebElement> cells = firstRow.findElements(By.tagName("td"));
236
```
237
238
### TakesScreenshot Interface
239
240
Screenshot capture capability for WebDriver and WebElement instances.
241
242
```java { .api }
243
/**
244
* TakesScreenshot interface for capturing screenshots
245
* Implemented by WebDriver (full page) and WebElement (element only)
246
*/
247
interface TakesScreenshot {
248
/**
249
* Capture screenshot in specified output format
250
* @param target - Output format (BASE64, BYTES, or FILE)
251
* @return Screenshot data in requested format
252
*/
253
<X> X getScreenshotAs(OutputType<X> target);
254
}
255
```
256
257
**Usage Examples:**
258
259
```java
260
import org.openqa.selenium.OutputType;
261
import org.openqa.selenium.TakesScreenshot;
262
import java.io.File;
263
import java.io.IOException;
264
import java.nio.file.Files;
265
import java.nio.file.Paths;
266
267
// Full page screenshot
268
TakesScreenshot screenshot = (TakesScreenshot) driver;
269
File fullPageFile = screenshot.getScreenshotAs(OutputType.FILE);
270
Files.copy(fullPageFile.toPath(), Paths.get("fullpage.png"));
271
272
// Element screenshot
273
WebElement loginForm = driver.findElement(By.id("loginForm"));
274
File elementFile = loginForm.getScreenshotAs(OutputType.FILE);
275
Files.copy(elementFile.toPath(), Paths.get("loginform.png"));
276
277
// Screenshot as base64 string (useful for embedding in reports)
278
String base64Screenshot = screenshot.getScreenshotAs(OutputType.BASE64);
279
280
// Screenshot as byte array
281
byte[] screenshotBytes = screenshot.getScreenshotAs(OutputType.BYTES);
282
```
283
284
### Element State Queries
285
286
Common patterns for checking element states and properties.
287
288
**Usage Examples:**
289
290
```java
291
WebElement element = driver.findElement(By.id("myElement"));
292
293
// Comprehensive element state check
294
public boolean isElementInteractable(WebElement element) {
295
return element.isDisplayed() && element.isEnabled();
296
}
297
298
// Check if element has specific CSS class
299
public boolean hasClass(WebElement element, String className) {
300
String classes = element.getAttribute("class");
301
return classes != null && classes.contains(className);
302
}
303
304
// Get element text with fallback to value attribute
305
public String getElementText(WebElement element) {
306
String text = element.getText();
307
if (text.isEmpty()) {
308
text = element.getAttribute("value");
309
}
310
return text;
311
}
312
313
// Check if input field is empty
314
public boolean isInputEmpty(WebElement input) {
315
return input.getDomProperty("value").isEmpty();
316
}
317
318
// Wait for element to be clickable
319
WebElement button = driver.findElement(By.id("submitButton"));
320
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
321
wait.until(ExpectedConditions.elementToBeClickable(button));
322
button.click();
323
```
324
325
### Form Element Interactions
326
327
Specialized interactions for different form element types.
328
329
**Usage Examples:**
330
331
```java
332
// Text input
333
WebElement textInput = driver.findElement(By.id("textField"));
334
textInput.clear();
335
textInput.sendKeys("New text value");
336
337
// Password input
338
WebElement passwordInput = driver.findElement(By.id("password"));
339
passwordInput.sendKeys("secretpassword");
340
341
// Textarea
342
WebElement textarea = driver.findElement(By.tagName("textarea"));
343
textarea.clear();
344
textarea.sendKeys("Line 1\nLine 2\nLine 3");
345
346
// Checkbox
347
WebElement checkbox = driver.findElement(By.id("agreeTerms"));
348
if (!checkbox.isSelected()) {
349
checkbox.click();
350
}
351
352
// Radio button
353
WebElement radioButton = driver.findElement(By.id("option1"));
354
radioButton.click();
355
356
// File upload
357
WebElement fileInput = driver.findElement(By.id("fileUpload"));
358
fileInput.sendKeys("/path/to/file.txt");
359
360
// Select dropdown (use Select class for better support)
361
WebElement selectElement = driver.findElement(By.id("country"));
362
Select select = new Select(selectElement);
363
select.selectByVisibleText("United States");
364
select.selectByValue("us");
365
select.selectByIndex(0);
366
```
367
368
### Color Utility Class
369
370
Utility class for parsing and manipulating CSS color values from elements.
371
372
```java { .api }
373
/**
374
* Color class for CSS color parsing and manipulation
375
* Converts between different color representations
376
*/
377
class Color {
378
/**
379
* Create Color from CSS color string
380
* @param cssColorString - CSS color value (hex, rgb, rgba, name, etc.)
381
* @return Color instance
382
*/
383
static Color fromString(String cssColorString);
384
385
/**
386
* Get color as hex string
387
* @return Hex color string (e.g., "#ff0000")
388
*/
389
String asHex();
390
391
/**
392
* Get color as RGB string
393
* @return RGB color string (e.g., "rgba(255, 0, 0, 1)")
394
*/
395
String asRgb();
396
397
/**
398
* Get color as RGBA string
399
* @return RGBA color string with alpha channel
400
*/
401
String asRgba();
402
403
/**
404
* Get red component (0-255)
405
* @return Red value
406
*/
407
short getRed();
408
409
/**
410
* Get green component (0-255)
411
* @return Green value
412
*/
413
short getGreen();
414
415
/**
416
* Get blue component (0-255)
417
* @return Blue value
418
*/
419
short getBlue();
420
421
/**
422
* Get alpha/opacity component (0.0-1.0)
423
* @return Alpha value
424
*/
425
float getAlpha();
426
}
427
```
428
429
**Usage Examples:**
430
431
```java
432
import org.openqa.selenium.support.Color;
433
434
// Get element color and parse it
435
WebElement element = driver.findElement(By.id("colorful-element"));
436
String cssColor = element.getCssValue("color");
437
Color color = Color.fromString(cssColor);
438
439
// Convert between color formats
440
String hexColor = color.asHex(); // "#ff0000"
441
String rgbColor = color.asRgb(); // "rgb(255, 0, 0)"
442
String rgbaColor = color.asRgba(); // "rgba(255, 0, 0, 1)"
443
444
// Get individual color components
445
short red = color.getRed(); // 255
446
short green = color.getGreen(); // 0
447
short blue = color.getBlue(); // 0
448
float alpha = color.getAlpha(); // 1.0
449
450
// Parse different CSS color formats
451
Color hexColor1 = Color.fromString("#ff0000");
452
Color hexColor2 = Color.fromString("#f00");
453
Color rgbColor1 = Color.fromString("rgb(255, 0, 0)");
454
Color rgbaColor1 = Color.fromString("rgba(255, 0, 0, 0.5)");
455
Color namedColor = Color.fromString("red");
456
457
// Verify element colors in tests
458
WebElement errorMessage = driver.findElement(By.className("error"));
459
Color errorColor = Color.fromString(errorMessage.getCssValue("color"));
460
assert errorColor.asHex().equals("#ff0000"); // Verify red color
461
```