What does WebElement clear() Do to TextBoxes?

SeleniumAutomation TestingTesting Tools

We can erase the contents from text boxes with Selenium webdriver. This is done with the clear() method. This method clears the edit box and also makes the field enabled.

First of all we need to identify the element with help of any of the locators like id, class, name, xpath or css and then apply sendKeys() method to type some text inside it. Next we shall apply the clear() method on it. To check if the edit box got cleared, we shall use getAttribute() method and pass value parameter as an argument to the method. We shall get blank value after clear() is applied.

Let us consider the below input box where we shall first enter some texts - Selenium and apply the clear() method. Finally fetch the value with get_attribute().


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class ClearEditBox{
   public static void main(String[] args) {
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element
      WebElement p=driver.findElement(By.name("q"));
      //enter text with sendKeys() then apply clear()
      //getAttribute() to obtain value
      String s= p.getAttribute("value");
      System.out.println("Value before clear : " + s);
      String n= p.getAttribute("value");
      System.out.println("Value after clear : " + n);


Updated on 18-Sep-2020 12:02:29