<div class="selenium-notes">
<h1>Web Element Operations with Java in Selenium</h1>
<p><strong>Web Element Operations</strong> are the actions performed on web elements such as text boxes, buttons, links, checkboxes, radio buttons, dropdowns, images, tables, and other HTML elements using Selenium WebDriver with Java.</p>
<p>After Selenium identifies an element using a locator, the returned <strong>WebElement</strong> can be used to interact with that element, retrieve information from it, verify its state, and perform user-like actions. Selenium's Java API provides methods such as <strong>click()</strong>, <strong>sendKeys()</strong>, <strong>clear()</strong>, <strong>getText()</strong>, <strong>getAttribute()</strong>, <strong>isDisplayed()</strong>, <strong>isEnabled()</strong>, and <strong>isSelected()</strong> for common element operations.</p>
<p><strong>Course Resource:</strong> <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Selenium Training</a> | <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a></p>
<hr>
<h2>1. What is a Web Element?</h2>
<p>A <strong>Web Element</strong> is an HTML element displayed or represented within a web page. Examples include input fields, buttons, links, checkboxes, radio buttons, dropdowns, headings, paragraphs, images, tables, and containers.</p>
<p>In Selenium Java, a web element is represented by the <strong>WebElement</strong> interface.</p>
<pre><code>WebElement username = driver.findElement(By.id("username"));</code></pre>
<p>Here:</p>
<ul>
<li><strong>driver</strong> is the WebDriver instance.</li>
<li><strong>findElement()</strong> searches for an element.</li>
<li><strong>By.id("username")</strong> is the locator.</li>
<li><strong>username</strong> is the WebElement reference.</li>
</ul>
<p>A WebElement can also act as a search context, which means Selenium can search for child elements inside an already located element.</p>
<h2>2. Why are Web Element Operations Important?</h2>
<p>Web element operations are the foundation of UI automation. Finding an element alone is not enough; Selenium must interact with the element to reproduce user actions and verify application behavior.</p>
<ul>
<li>Enter data into forms.</li>
<li>Click buttons.</li>
<li>Open links.</li>
<li>Select checkboxes and radio buttons.</li>
<li>Read text from pages.</li>
<li>Retrieve attribute values.</li>
<li>Check whether elements are visible.</li>
<li>Check whether elements are enabled.</li>
<li>Check whether checkboxes or radio buttons are selected.</li>
<li>Work with dropdowns.</li>
<li>Validate application behavior.</li>
<li>Automate complete business workflows.</li>
</ul>
<h2>3. Basic Web Element Operation Flow</h2>
<pre><code>Open Browser
|
v
Open Web Application
|
v
Inspect HTML
|
v
Choose Locator
|
v
findElement()
|
v
Get WebElement
|
v
Perform Operation
|
v
Validate Result
|
v
Continue Test
|
v
driver.quit()</code></pre>
<h2>4. Basic WebElement Syntax</h2>
<p>The general syntax for locating a web element is:</p>
<pre><code>WebElement element = driver.findElement(By.id("elementId"));</code></pre>
<p>After obtaining the WebElement, Selenium operations can be performed on it.</p>
<pre><code>element.click();</code></pre>
<h2>5. Important WebElement Methods</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Method</th><th>Purpose</th></tr>
<tr><td>click()</td><td>Clicks the element</td></tr>
<tr><td>sendKeys()</td><td>Enters text or keyboard input</td></tr>
<tr><td>clear()</td><td>Clears text from an editable field</td></tr>
<tr><td>getText()</td><td>Returns visible rendered text</td></tr>
<tr><td>getAttribute()</td><td>Retrieves an attribute or runtime property value</td></tr>
<tr><td>isDisplayed()</td><td>Checks whether the element is displayed</td></tr>
<tr><td>isEnabled()</td><td>Checks whether the element is enabled</td></tr>
<tr><td>isSelected()</td><td>Checks whether a selectable element is selected</td></tr>
<tr><td>getTagName()</td><td>Returns the HTML tag name</td></tr>
<tr><td>getCssValue()</td><td>Returns a CSS property value</td></tr>
<tr><td>getDomAttribute()</td><td>Retrieves the declared DOM attribute value</td></tr>
<tr><td>getDomProperty()</td><td>Retrieves the current DOM property value</td></tr>
</table>
<h2>6. Locating a Web Element</h2>
<p>Before performing an operation, Selenium must identify the target element using a locator.</p>
<pre><code>WebElement username =
driver.findElement(By.id("username"));</code></pre>
<p>Common locator strategies include:</p>
<ul>
<li>ID</li>
<li>Name</li>
<li>Class Name</li>
<li>Tag Name</li>
<li>Link Text</li>
<li>Partial Link Text</li>
<li>CSS Selector</li>
<li>XPath</li>
</ul>
<p>The <strong>findElement()</strong> method returns the first matching element, while <strong>findElements()</strong> returns a collection of matching elements.</p>
<h2>7. click() Operation</h2>
<p>The <strong>click()</strong> method is used to click buttons, links, checkboxes, radio buttons, menu items, and other clickable elements.</p>
<pre><code>WebElement loginButton =
driver.findElement(By.id("login"));
loginButton.click();</code></pre>
<h3>Example</h3>
<pre><code>driver.findElement(By.cssSelector("button.login")).click();</code></pre>
<h3>Real-World Example</h3>
<pre><code>WebElement submitButton =
driver.findElement(By.cssSelector("button[type='submit']"));
submitButton.click();</code></pre>
<h2>8. sendKeys() Operation</h2>
<p>The <strong>sendKeys()</strong> method is used to enter text or keyboard input into an element such as a text box, search field, username field, password field, or textarea.</p>
<pre><code>WebElement username =
driver.findElement(By.id("username"));
username.sendKeys("admin");</code></pre>
<h3>Password Example</h3>
<pre><code>WebElement password =
driver.findElement(By.id("password"));
password.sendKeys("Password123");</code></pre>
<h2>9. clear() Operation</h2>
<p>The <strong>clear()</strong> method removes the existing text from an editable element.</p>
<pre><code>WebElement searchBox =
driver.findElement(By.id("search"));
searchBox.clear();
searchBox.sendKeys("Laptop");</code></pre>
<h3>When to Use clear()</h3>
<ul>
<li>When a field already contains text.</li>
<li>When replacing existing test data.</li>
<li>When testing form editing.</li>
<li>When reusing the same input field during a test.</li>
</ul>
<h2>10. getText() Operation</h2>
<p>The <strong>getText()</strong> method retrieves the visible rendered text of an element.</p>
<pre><code>WebElement message =
driver.findElement(By.id("message"));
String text = message.getText();
System.out.println("Message: " + text);</code></pre>
<h2>11. getAttribute() Operation</h2>
<p>The <strong>getAttribute()</strong> method can be used to retrieve a value associated with an element's attribute or runtime property.</p>
<pre><code>WebElement username =
driver.findElement(By.id("username"));
String value = username.getAttribute("value");
System.out.println(value);</code></pre>
<h3>Getting href</h3>
<pre><code>WebElement link =
driver.findElement(By.linkText("Home"));
String href = link.getAttribute("href");
System.out.println("Link URL: " + href);</code></pre>
<h3>Getting class</h3>
<pre><code>String className =
driver.findElement(By.id("login"))
.getAttribute("class");
System.out.println(className);</code></pre>
<h2>12. getDomAttribute() and getDomProperty()</h2>
<p>Modern Selenium Java APIs distinguish between a declared DOM attribute and a current DOM property. This distinction is useful when testing values that may change after page load.</p>
<pre><code>WebElement input =
driver.findElement(By.id("username"));
String attributeValue =
input.getDomAttribute("value");
String propertyValue =
input.getDomProperty("value");</code></pre>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Method</th><th>Typical Use</th></tr>
<tr><td>getAttribute()</td><td>Reads an attribute or applicable runtime value</td></tr>
<tr><td>getDomAttribute()</td><td>Reads the DOM attribute</td></tr>
<tr><td>getDomProperty()</td><td>Reads the current DOM property</td></tr>
</table>
<h2>13. isDisplayed() Operation</h2>
<p>The <strong>isDisplayed()</strong> method checks whether an element is displayed in the current browsing context.</p>
<pre><code>WebElement username =
driver.findElement(By.id("username"));
if (username.isDisplayed()) {
System.out.println("Username field is visible");
}</code></pre>
<h2>14. isEnabled() Operation</h2>
<p>The <strong>isEnabled()</strong> method checks whether an element is enabled for interaction.</p>
<pre><code>WebElement loginButton =
driver.findElement(By.id("login"));
if (loginButton.isEnabled()) {
loginButton.click();
}</code></pre>
<h3>Disabled Button Example</h3>
<pre><code>WebElement submit =
driver.findElement(By.id("submit"));
System.out.println(
"Enabled: " + submit.isEnabled()
);</code></pre>
<h2>15. isSelected() Operation</h2>
<p>The <strong>isSelected()</strong> method is commonly used with checkboxes, radio buttons, and other selectable elements.</p>
<pre><code>WebElement checkbox =
driver.findElement(By.id("terms"));
if (!checkbox.isSelected()) {
checkbox.click();
}</code></pre>
<h2>16. Selecting a Radio Button</h2>
<pre><code>WebElement maleRadio =
driver.findElement(By.id("male"));
if (!maleRadio.isSelected()) {
maleRadio.click();
}</code></pre>
<h2>17. Selecting a Checkbox</h2>
<pre><code>WebElement terms =
driver.findElement(By.id("terms"));
if (!terms.isSelected()) {
terms.click();
}</code></pre>
<h2>18. Deselecting a Checkbox</h2>
<p>Selenium does not provide a direct <strong>deselect()</strong> operation for a normal checkbox. The common approach is to check its current state and click it only when it is selected.</p>
<pre><code>WebElement checkbox =
driver.findElement(By.id("newsletter"));
if (checkbox.isSelected()) {
checkbox.click();
}</code></pre>
<h2>19. Checking Multiple Element States</h2>
<pre><code>WebElement element =
driver.findElement(By.id("submit"));
System.out.println("Displayed: " + element.isDisplayed());
System.out.println("Enabled: " + element.isEnabled());
System.out.println("Selected: " + element.isSelected());</code></pre>
<h2>20. getTagName() Operation</h2>
<p>The <strong>getTagName()</strong> method returns the HTML tag name of an element.</p>
<pre><code>WebElement element =
driver.findElement(By.id("username"));
String tagName = element.getTagName();
System.out.println("Tag: " + tagName);</code></pre>
<p>For example, the returned value may be <strong>input</strong>, <strong>button</strong>, <strong>div</strong>, or <strong>a</strong>.</p>
<h2>21. getCssValue() Operation</h2>
<p>The <strong>getCssValue()</strong> method retrieves the value of a CSS property associated with an element.</p>
<pre><code>WebElement heading =
driver.findElement(By.tagName("h1"));
String fontSize =
heading.getCssValue("font-size");
System.out.println("Font Size: " + fontSize);</code></pre>
<h3>Another Example</h3>
<pre><code>String display =
heading.getCssValue("display");
System.out.println("Display: " + display);</code></pre>
<h2>22. Working with Text Boxes</h2>
<p>Text boxes are among the most frequently used web elements in automation.</p>
<pre><code>WebElement username =
driver.findElement(By.id("username"));
username.clear();
username.sendKeys("testuser");</code></pre>
<h3>Complete Form Example</h3>
<pre><code>WebElement firstName =
driver.findElement(By.id("firstName"));
WebElement lastName =
driver.findElement(By.id("lastName"));
firstName.sendKeys("John");
lastName.sendKeys("Smith");</code></pre>
<h2>23. Working with Password Fields</h2>
<pre><code>WebElement password =
driver.findElement(By.id("password"));
password.clear();
password.sendKeys("Password123");</code></pre>
<h2>24. Working with Textarea</h2>
<p>A textarea can be handled similarly to a normal text input.</p>
<pre><code>WebElement comments =
driver.findElement(By.id("comments"));
comments.sendKeys("This is a Selenium test.");</code></pre>
<h2>25. Working with Buttons</h2>
<pre><code>WebElement loginButton =
driver.findElement(By.id("loginButton"));
if (loginButton.isDisplayed() &&
loginButton.isEnabled()) {
loginButton.click();
}</code></pre>
<h2>26. Working with Links</h2>
<pre><code>WebElement homeLink =
driver.findElement(By.linkText("Home"));
homeLink.click();</code></pre>
<h3>Reading Link URL</h3>
<pre><code>WebElement link =
driver.findElement(By.linkText("Products"));
String url =
link.getAttribute("href");
System.out.println(url);</code></pre>
<h2>27. Working with Images</h2>
<p>Images can be located using attributes such as <strong>id</strong>, <strong>alt</strong>, <strong>src</strong>, CSS selectors, or XPath.</p>
<pre><code>WebElement logo =
driver.findElement(By.cssSelector("img.logo"));
String source =
logo.getAttribute("src");
System.out.println("Image URL: " + source);</code></pre>
<h2>28. Working with Dropdowns</h2>
<p>For a standard HTML <strong><select></strong> element, Selenium provides the <strong>Select</strong> class.</p>
<pre><code>import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
WebElement countryElement =
driver.findElement(By.id("country"));
Select country =
new Select(countryElement);
country.selectByVisibleText("India");</code></pre>
<h3>Select by Value</h3>
<pre><code>country.selectByValue("IN");</code></pre>
<h3>Select by Index</h3>
<pre><code>country.selectByIndex(2);</code></pre>
<h3>Get All Dropdown Options</h3>
<pre><code>List<WebElement> options =
country.getOptions();
for (WebElement option : options) {
System.out.println(option.getText());
}</code></pre>
<h2>29. Checking Selected Dropdown Option</h2>
<pre><code>WebElement selectedOption =
country.getFirstSelectedOption();
System.out.println(
"Selected: " + selectedOption.getText()
);</code></pre>
<h2>30. Handling Multiple Select Dropdowns</h2>
<p>Some HTML select elements allow multiple options to be selected.</p>
<pre><code>if (country.isMultiple()) {
country.selectByValue("IN");
country.selectByValue("US");
}</code></pre>
<h2>31. Working with Tables</h2>
<p>Tables contain rows and cells that can be located and processed using WebElement collections.</p>
<pre><code>List<WebElement> rows =
driver.findElements(By.cssSelector("table tbody tr"));
for (WebElement row : rows) {
System.out.println(row.getText());
}</code></pre>
<h3>Reading Table Cells</h3>
<pre><code>List<WebElement> cells =
driver.findElements(By.cssSelector("table tbody tr td"));
for (WebElement cell : cells) {
System.out.println(cell.getText());
}</code></pre>
<h2>32. Working with Lists of Web Elements</h2>
<p>The <strong>findElements()</strong> method returns a list of matching WebElement objects. If nothing matches, Selenium returns an empty list.</p>
<pre><code>List<WebElement> buttons =
driver.findElements(By.tagName("button"));
System.out.println(
"Buttons: " + buttons.size()
);</code></pre>
<h3>Loop Through Elements</h3>
<pre><code>for (WebElement button : buttons) {
System.out.println(button.getText());
}</code></pre>
<h2>33. Performing Operations on Multiple Elements</h2>
<pre><code>List<WebElement> checkboxes =
driver.findElements(
By.cssSelector("input[type='checkbox']")
);
for (WebElement checkbox : checkboxes) {
if (!checkbox.isSelected()) {
checkbox.click();
}
}</code></pre>
<h2>34. Checking Element Text</h2>
<pre><code>WebElement message =
driver.findElement(By.id("message"));
String actualMessage =
message.getText();
if (actualMessage.equals("Login successful")) {
System.out.println("Message verified");
}</code></pre>
<h2>35. Checking an Input Value</h2>
<p>For input fields, the entered text is commonly represented by the element's <strong>value</strong> property.</p>
<pre><code>WebElement username =
driver.findElement(By.id("username"));
username.sendKeys("admin");
String value =
username.getAttribute("value");
System.out.println("Entered: " + value);</code></pre>
<h2>36. Getting Element Attributes</h2>
<pre><code>WebElement button =
driver.findElement(By.id("login"));
String id =
button.getAttribute("id");
String className =
button.getAttribute("class");
String type =
button.getAttribute("type");
System.out.println("ID: " + id);
System.out.println("Class: " + className);
System.out.println("Type: " + type);</code></pre>
<h2>37. Verifying Element Visibility</h2>
<pre><code>WebElement errorMessage =
driver.findElement(By.id("error"));
if (errorMessage.isDisplayed()) {
System.out.println(
"Error message is visible"
);
}</code></pre>
<h2>38. Verifying Element Availability</h2>
<pre><code>WebElement submit =
driver.findElement(By.id("submit"));
if (submit.isEnabled()) {
System.out.println(
"Submit button is enabled"
);
}</code></pre>
<h2>39. Web Element Operations with Explicit Wait</h2>
<p>Modern web applications may load or update elements asynchronously. In such cases, a test may need to wait for a required condition before performing an operation.</p>
<pre><code>import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ElementWaitExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.get("https://example.com");
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
WebElement username =
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("username")
)
);
username.sendKeys("admin");
} finally {
driver.quit();
}
}
}</code></pre>
<h2>40. ElementClickInterceptedException</h2>
<p>Sometimes Selenium identifies an element correctly but another element, overlay, popup, or UI component prevents the click operation.</p>
<p>Example situations include:</p>
<ul>
<li>Cookie banners covering the button.</li>
<li>Modal dialogs covering the page.</li>
<li>Loading overlays.</li>
<li>Animations or transitions.</li>
<li>Another element positioned above the target.</li>
</ul>
<p>Use appropriate synchronization and make sure the intended element is interactable before clicking.</p>
<h2>41. StaleElementReferenceException</h2>
<p>A WebElement reference can become stale when the DOM is refreshed or the element is replaced.</p>
<pre><code>WebElement username =
driver.findElement(By.id("username"));
driver.navigate().refresh();
username =
driver.findElement(By.id("username"));
username.sendKeys("admin");</code></pre>
<h2>42. NoSuchElementException</h2>
<p>A <strong>NoSuchElementException</strong> can occur when Selenium cannot find an element using the supplied locator.</p>
<pre><code>WebElement username =
driver.findElement(By.id("wrongId"));</code></pre>
<p>Possible causes include:</p>
<ul>
<li>Incorrect locator.</li>
<li>Element not yet loaded.</li>
<li>Wrong page.</li>
<li>Element inside an iframe.</li>
<li>DOM changed after the element was located.</li>
<li>Incorrect browsing context.</li>
</ul>
<h2>43. Handling Elements Inside an iframe</h2>
<p>If an element belongs to an iframe, Selenium must first switch into the appropriate frame before interacting with the element.</p>
<pre><code>WebElement frame =
driver.findElement(By.id("paymentFrame"));
driver.switchTo().frame(frame);
WebElement cardNumber =
driver.findElement(By.id("cardNumber"));
cardNumber.sendKeys("4111111111111111");
driver.switchTo().defaultContent();</code></pre>
<h2>44. Handling Elements in Nested DOM Structures</h2>
<p>WebElement also acts as a search context, so an element can be used as the starting point for locating descendants.</p>
<pre><code>WebElement loginForm =
driver.findElement(By.id("loginForm"));
WebElement username =
loginForm.findElement(
By.name("username")
);
username.sendKeys("admin");</code></pre>
<p>This can make locators more scoped and readable when a specific container has been identified.</p>
<h2>45. Working with Element Collections Inside a Container</h2>
<pre><code>WebElement productList =
driver.findElement(By.id("products"));
List<WebElement> products =
productList.findElements(By.cssSelector(".product"));
for (WebElement product : products) {
System.out.println(product.getText());
}</code></pre>
<h2>46. Keyboard Operations with WebElement</h2>
<p>The <strong>sendKeys()</strong> method can also send keyboard keys to an element.</p>
<pre><code>import org.openqa.selenium.Keys;
WebElement search =
driver.findElement(By.id("search"));
search.sendKeys("Selenium");
search.sendKeys(Keys.ENTER);</code></pre>
<h3>Ctrl + A Example</h3>
<pre><code>search.sendKeys(Keys.CONTROL, "a");</code></pre>
<h3>Backspace Example</h3>
<pre><code>search.sendKeys(Keys.BACK_SPACE);</code></pre>
<h2>47. Tab Key Operation</h2>
<pre><code>WebElement username =
driver.findElement(By.id("username"));
username.sendKeys("admin");
username.sendKeys(Keys.TAB);</code></pre>
<h2>48. Enter Key Operation</h2>
<pre><code>WebElement searchBox =
driver.findElement(By.name("q"));
searchBox.sendKeys("Selenium WebDriver");
searchBox.sendKeys(Keys.ENTER);</code></pre>
<h2>49. Form Submission</h2>
<p>For many modern applications, clicking the appropriate submit button is preferred. In cases where the form element supports submission, the form can also be submitted through the relevant Selenium API.</p>
<pre><code>WebElement form =
driver.findElement(By.id("loginForm"));
form.submit();</code></pre>
<h2>50. Mouse Operations and Web Elements</h2>
<p>For advanced mouse interactions, Selenium provides the <strong>Actions</strong> API. The WebElement can be supplied as the target of the mouse operation.</p>
<pre><code>import org.openqa.selenium.interactions.Actions;
WebElement menu =
driver.findElement(By.id("menu"));
Actions actions =
new Actions(driver);
actions.moveToElement(menu).perform();</code></pre>
<h2>51. Double Click on a Web Element</h2>
<pre><code>WebElement element =
driver.findElement(By.id("item"));
Actions actions =
new Actions(driver);
actions.doubleClick(element).perform();</code></pre>
<h2>52. Right Click on a Web Element</h2>
<pre><code>WebElement element =
driver.findElement(By.id("item"));
Actions actions =
new Actions(driver);
actions.contextClick(element).perform();</code></pre>
<h2>53. Drag and Drop</h2>
<pre><code>WebElement source =
driver.findElement(By.id("source"));
WebElement target =
driver.findElement(By.id("target"));
Actions actions =
new Actions(driver);
actions.dragAndDrop(source, target).perform();</code></pre>
<h2>54. Scrolling to a Web Element</h2>
<p>When an element is outside the visible area, scrolling may be required before interaction.</p>
<pre><code>WebElement element =
driver.findElement(By.id("footer"));
JavascriptExecutor js =
(JavascriptExecutor) driver;
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
element
);</code></pre>
<h2>55. Clicking Through JavaScript</h2>
<p>JavaScript execution can sometimes be useful for special situations, but normal WebDriver interaction should generally be preferred when the element is properly interactable.</p>
<pre><code>WebElement button =
driver.findElement(By.id("login"));
JavascriptExecutor js =
(JavascriptExecutor) driver;
js.executeScript(
"arguments[0].click();",
button
);</code></pre>
<h2>56. Reading Element HTML</h2>
<p>An element's HTML-related attributes can be inspected to help verify its structure and state.</p>
<pre><code>WebElement element =
driver.findElement(By.id("username"));
String outerHtml =
element.getAttribute("outerHTML");
System.out.println(outerHtml);</code></pre>
<h2>57. Element Operation with Assertions</h2>
<p>Web element operations are frequently combined with assertions to verify application behavior.</p>
<pre><code>import static org.testng.Assert.assertTrue;
WebElement message =
driver.findElement(By.id("success"));
assertTrue(message.isDisplayed());</code></pre>
<h3>Text Assertion</h3>
<pre><code>import static org.testng.Assert.assertEquals;
String actual =
driver.findElement(By.id("message"))
.getText();
assertEquals(actual, "Login successful");</code></pre>
<h2>58. Complete Login Web Element Operation Example</h2>
<pre><code>import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class LoginElementOperations {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.manage().window().maximize();
driver.get("https://example.com");
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
WebElement username =
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("username")
)
);
WebElement password =
driver.findElement(By.id("password"));
WebElement loginButton =
driver.findElement(By.id("login"));
username.clear();
username.sendKeys("admin");
password.clear();
password.sendKeys("Password123");
if (loginButton.isDisplayed() &&
loginButton.isEnabled()) {
loginButton.click();
}
} finally {
driver.quit();
}
}
}</code></pre>
<h2>59. Complete Form Operations Example</h2>
<pre><code>WebElement firstName =
driver.findElement(By.id("firstName"));
WebElement lastName =
driver.findElement(By.id("lastName"));
WebElement email =
driver.findElement(By.id("email"));
WebElement terms =
driver.findElement(By.id("terms"));
WebElement submit =
driver.findElement(
By.cssSelector("button[type='submit']")
);
firstName.clear();
firstName.sendKeys("John");
lastName.clear();
lastName.sendKeys("Smith");
email.clear();
email.sendKeys("[email protected]");
if (!terms.isSelected()) {
terms.click();
}
if (submit.isEnabled()) {
submit.click();
}</code></pre>
<h2>60. Real-World E-Commerce Web Element Operations</h2>
<pre><code>WebElement searchBox =
driver.findElement(By.id("search"));
searchBox.clear();
searchBox.sendKeys("Laptop");
searchBox.sendKeys(Keys.ENTER);
WebElement product =
driver.findElement(
By.cssSelector(".product-card")
);
System.out.println(
"Product: " + product.getText()
);
WebElement addToCart =
product.findElement(
By.cssSelector(".add-to-cart")
);
if (addToCart.isEnabled()) {
addToCart.click();
}</code></pre>
<h2>61. Real-World Registration Form Operations</h2>
<pre><code>WebElement firstName =
driver.findElement(By.id("firstName"));
WebElement lastName =
driver.findElement(By.id("lastName"));
WebElement email =
driver.findElement(By.name("email"));
WebElement password =
driver.findElement(By.name("password"));
WebElement terms =
driver.findElement(By.id("terms"));
firstName.sendKeys("John");
lastName.sendKeys("Smith");
email.sendKeys("[email protected]");
password.sendKeys("Password123");
if (!terms.isSelected()) {
terms.click();
}</code></pre>
<h2>62. Page Object Model and Web Element Operations</h2>
<p>In the Page Object Model, locators and element operations are usually organized inside page classes. This separates page interaction logic from test scenarios and improves maintainability.</p>
<pre><code>import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPage {
private WebDriver driver;
private By usernameField =
By.id("username");
private By passwordField =
By.id("password");
private By loginButton =
By.id("login");
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public void enterUsername(String value) {
driver.findElement(usernameField)
.clear();
driver.findElement(usernameField)
.sendKeys(value);
}
public void enterPassword(String value) {
driver.findElement(passwordField)
.clear();
driver.findElement(passwordField)
.sendKeys(value);
}
public void clickLogin() {
driver.findElement(loginButton)
.click();
}
}</code></pre>
<h2>63. Web Element Operations in PageFactory</h2>
<p>Selenium's Java support package also provides PageFactory and annotations such as <strong>@FindBy</strong> for Page Object implementations.</p>
<pre><code>import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class LoginPage {
@FindBy(id = "username")
private WebElement username;
@FindBy(id = "password")
private WebElement password;
@FindBy(id = "login")
private WebElement loginButton;
public LoginPage(WebDriver driver) {
PageFactory.initElements(driver, this);
}
public void login(
String user,
String pass
) {
username.clear();
username.sendKeys(user);
password.clear();
password.sendKeys(pass);
loginButton.click();
}
}</code></pre>
<h2>64. Web Element Operations with Dynamic Elements</h2>
<p>Dynamic elements may not be immediately available or may change after an AJAX request. In such situations, combine reliable locators with explicit waits.</p>
<pre><code>WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
WebElement button =
wait.until(
ExpectedConditions.elementToBeClickable(
By.id("submit")
)
);
button.click();</code></pre>
<h2>65. Web Element Operations with Multiple Matching Elements</h2>
<pre><code>List<WebElement> products =
driver.findElements(
By.cssSelector(".product")
);
for (WebElement product : products) {
String name = product.getText();
System.out.println(
"Product: " + name
);
}</code></pre>
<h2>66. Web Element Operation Decision Flow</h2>
<pre><code>Locate Element
|
v
Get WebElement
|
v
Is it Displayed?
|
Yes
|
v
Is it Enabled?
|
Yes
|
v
Choose Operation
|
+---- sendKeys()
|
+---- click()
|
+---- clear()
|
+---- getText()
|
+---- getAttribute()
|
+---- isSelected()
|
+---- getCssValue()
|
v
Validate Result</code></pre>
<h2>67. Common Web Element Exceptions</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Exception</th><th>Typical Cause</th><th>Possible Solution</th></tr>
<tr><td>NoSuchElementException</td><td>Element cannot be found</td><td>Verify locator, page state, frame, and synchronization</td></tr>
<tr><td>StaleElementReferenceException</td><td>DOM changed after locating the element</td><td>Locate the element again</td></tr>
<tr><td>ElementClickInterceptedException</td><td>Another element blocks the click</td><td>Check overlays, scrolling, and synchronization</td></tr>
<tr><td>ElementNotInteractableException</td><td>Element cannot currently receive the requested interaction</td><td>Check visibility, enabled state, and page state</td></tr>
<tr><td>InvalidElementStateException</td><td>Element is in an unsuitable state for the requested operation</td><td>Verify the element type and current state</td></tr>
<tr><td>TimeoutException</td><td>Wait condition was not satisfied within the timeout</td><td>Check locator, condition, page state, and timeout</td></tr>
</table>
<h2>68. Common Web Element Operation Mistakes</h2>
<ul>
<li>Trying to interact with an element before locating it.</li>
<li>Using an unstable locator.</li>
<li>Typing into a disabled field.</li>
<li>Clicking before an element becomes interactable.</li>
<li>Ignoring overlays and modal dialogs.</li>
<li>Using a stale WebElement reference after the DOM changes.</li>
<li>Using getText() when the required value is actually stored in an input's value property.</li>
<li>Using Select with a custom dropdown that is not an HTML select element.</li>
<li>Failing to switch into an iframe before interacting with its elements.</li>
<li>Using JavaScript unnecessarily instead of normal WebDriver interaction.</li>
<li>Not using explicit waits for asynchronous page behavior.</li>
<li>Not closing the browser after the test.</li>
</ul>
<h2>69. Best Practices for Web Element Operations</h2>
<ol>
<li>Use stable and unique locators.</li>
<li>Keep locators readable and maintainable.</li>
<li>Use explicit waits for dynamic elements when synchronization is required.</li>
<li>Check element state when the workflow requires it.</li>
<li>Use clear() before sendKeys() when replacing existing input.</li>
<li>Use getAttribute("value") or the appropriate property when validating input values.</li>
<li>Use getText() for rendered text.</li>
<li>Use isDisplayed(), isEnabled(), and isSelected() when state verification is needed.</li>
<li>Use the Select class only for standard HTML select elements.</li>
<li>Use Actions for advanced mouse interactions.</li>
<li>Use JavaScript execution only when appropriate for the test scenario.</li>
<li>Re-locate elements after a DOM refresh when necessary.</li>
<li>Keep element operations inside Page Object classes in larger frameworks.</li>
<li>Use meaningful variable and method names.</li>
<li>Always clean up the WebDriver session with driver.quit().</li>
</ol>
<h2>70. WebElement vs WebDriver</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>WebDriver</th><th>WebElement</th></tr>
<tr><td>Controls the browser</td><td>Represents an HTML element</td></tr>
<tr><td>Opens and navigates pages</td><td>Interacts with individual elements</td></tr>
<tr><td>Manages browser windows</td><td>Manages element-level operations</td></tr>
<tr><td>Can locate elements</td><td>Can perform actions on located elements</td></tr>
<tr><td>Example: driver.get()</td><td>Example: element.click()</td></tr>
<tr><td>Example: driver.navigate().back()</td><td>Example: element.sendKeys()</td></tr>
</table>
<h2>71. WebElement Operation Quick Revision</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Operation</th><th>Java Method</th><th>Purpose</th></tr>
<tr><td>Click</td><td>click()</td><td>Clicks an element</td></tr>
<tr><td>Enter Text</td><td>sendKeys()</td><td>Enters text or keyboard input</td></tr>
<tr><td>Clear Text</td><td>clear()</td><td>Removes existing editable text</td></tr>
<tr><td>Read Text</td><td>getText()</td><td>Reads rendered text</td></tr>
<tr><td>Read Attribute</td><td>getAttribute()</td><td>Reads an attribute or applicable runtime value</td></tr>
<tr><td>Read DOM Attribute</td><td>getDomAttribute()</td><td>Reads a declared DOM attribute</td></tr>
<tr><td>Read DOM Property</td><td>getDomProperty()</td><td>Reads a current DOM property</td></tr>
<tr><td>Visibility</td><td>isDisplayed()</td><td>Checks whether element is displayed</td></tr>
<tr><td>Enabled State</td><td>isEnabled()</td><td>Checks whether element is enabled</td></tr>
<tr><td>Selected State</td><td>isSelected()</td><td>Checks selected state</td></tr>
<tr><td>Tag Name</td><td>getTagName()</td><td>Returns HTML tag name</td></tr>
<tr><td>CSS Value</td><td>getCssValue()</td><td>Reads a CSS property</td></tr>
</table>
<h2>72. Practical Project: Web Element Operations Practice</h2>
<p>Build a Selenium Java automation project that demonstrates different WebElement operations on a registration or login page.</p>
<h3>Project Requirements</h3>
<ul>
<li>Launch Chrome browser.</li>
<li>Open a test web application.</li>
<li>Locate username and password fields.</li>
<li>Clear existing values.</li>
<li>Enter username and password.</li>
<li>Check whether the login button is displayed.</li>
<li>Check whether the login button is enabled.</li>
<li>Click the login button.</li>
<li>Read the success message.</li>
<li>Verify the message text.</li>
<li>Read selected attributes.</li>
<li>Close the browser using driver.quit().</li>
</ul>
<h2>73. Practical Complete Web Element Operations Program</h2>
<pre><code>import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class WebElementOperations {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.manage().window().maximize();
driver.get(
"https://www.selenium.dev/selenium/web/web-form.html"
);
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
WebElement textBox =
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.name("my-text")
)
);
System.out.println(
"Displayed: " + textBox.isDisplayed()
);
System.out.println(
"Enabled: " + textBox.isEnabled()
);
textBox.clear();
textBox.sendKeys("Selenium with Java");
WebElement submitButton =
wait.until(
ExpectedConditions.elementToBeClickable(
By.cssSelector("button")
)
);
submitButton.click();
WebElement message =
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("message")
)
);
System.out.println(
"Message: " + message.getText()
);
} finally {
driver.quit();
}
}
}</code></pre>
<h2>74. Interview Questions on Web Element Operations</h2>
<h3>Q1. What is WebElement in Selenium?</h3>
<p>WebElement is the Selenium Java interface used to represent an HTML element and perform operations on that element.</p>
<h3>Q2. What is the use of click()?</h3>
<p>The click() method is used to perform a click operation on a clickable web element such as a button, link, checkbox, or radio button.</p>
<h3>Q3. What is the difference between clear() and sendKeys()?</h3>
<p><strong>clear()</strong> removes existing text from an editable field, while <strong>sendKeys()</strong> enters text or keyboard input into the element.</p>
<h3>Q4. What is the use of getText()?</h3>
<p>getText() retrieves the rendered visible text of an element.</p>
<h3>Q5. How do you get the value entered in a text box?</h3>
<p>A common approach is to retrieve the value using the element's value attribute or property.</p>
<pre><code>String value =
driver.findElement(By.id("username"))
.getAttribute("value");</code></pre>
<h3>Q6. What is isDisplayed()?</h3>
<p>isDisplayed() checks whether the element is displayed in the current browsing context.</p>
<h3>Q7. What is isEnabled()?</h3>
<p>isEnabled() checks whether the element is enabled for interaction.</p>
<h3>Q8. What is isSelected()?</h3>
<p>isSelected() checks whether a selectable element such as a checkbox or radio button is currently selected.</p>
<h3>Q9. Can WebElement locate another element?</h3>
<p>Yes. WebElement is a SearchContext, so it can be used with findElement() and findElements() to search within that element's context.</p>
<h3>Q10. How do you handle a stale WebElement?</h3>
<p>When the DOM has changed and the previous reference is stale, locate the element again before performing the operation.</p>
<h3>Q11. How do you handle a dropdown?</h3>
<p>For a standard HTML select element, locate it and create a Selenium Select object, then use methods such as selectByVisibleText(), selectByValue(), or selectByIndex().</p>
<h3>Q12. Why are waits important for WebElement operations?</h3>
<p>Modern web applications may update the DOM asynchronously. Appropriate waits help synchronize the test with the required element state before performing an operation.</p>
<h2>75. Final Summary</h2>
<p><strong>Web Element Operations</strong> are the core actions used to automate interactions with web pages using Selenium WebDriver and Java. After locating an element, Selenium allows testers to click it, enter text, clear fields, read text and attributes, check visibility and enabled state, verify selections, work with dropdowns, perform keyboard operations, and execute advanced mouse interactions.</p>
<p>The most frequently used methods include <strong>click(), sendKeys(), clear(), getText(), getAttribute(), isDisplayed(), isEnabled(), isSelected(), getTagName(), and getCssValue()</strong>. Reliable automation also requires stable locators, proper synchronization, handling of dynamic DOM changes, and correct management of frames and special UI components.</p>
<p>In professional Selenium frameworks, WebElement operations are commonly organized through the Page Object Model, where page-specific locators and interactions are maintained separately from test cases. This improves readability, reuse, and maintainability.</p>
<hr>
<h2>76. Course Resources</h2>
<p><strong>Learn more about Selenium Automation Testing:</strong></p>
<p><a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Selenium Training</a></p>
<p><strong>Register for a course demo:</strong></p>
<p><a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a></p>
</div>