We use cookies to analyze site traffic and show personalized ads. You can accept all cookies or decline personalized advertising.
Learn more in our Privacy Policy.
Resetting the content of an editable element before typing new data.
The clear() command removes the existing content from an editable element.
clear(), sendKeys() will append to the old text.clear() → sendKeys().clear() on elements that are editable and enabled. If the field is readonly or disabled, Selenium throws InvalidElementStateException.Element ID: lesson5-input
Contains 33 characters
Press the "Clear" button to empty the field. Notice how the character count drops to 0.
12345WebElement oldDataInput = driver.findElement(By.id("lesson5-input"));
oldDataInput.clear();
oldDataInput.sendKeys("New fresh text");
driver.quit();"New fresh text" into the now-empty field. This is the standard pattern.Get into the habit of always calling clear() before sendKeys() in form fields. It prevents surprises like "OldTextNewText".
Remember: clear() only works on editable, enabled elements. If the field is readonly or disabled, Selenium will throw InvalidElementStateException.