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().

Example

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) {
System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.google.com/");
      // identify element
      WebElement p=driver.findElement(By.name("q"));
      //enter text with sendKeys() then apply clear()
      p.sendKeys("Selenium");
      //getAttribute() to obtain value
      String s= p.getAttribute("value");
      System.out.println("Value before clear : " + s);
      p.clear();
      String n= p.getAttribute("value");
      System.out.println("Value after clear : " + n);
      driver.close();
   }
}

Output

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

Advertisements