Selenium clear method

Selenium clear() method

Selenium clear() method is used to clear text from input textbox or text area. Clear() method required when you enter some text in textbox or some text is already present in textbox and you want to erase those texts to type new text in it.

Selenium clear method

  • Clear() method is part of WebElement interface which extends SearchContext nd TakesScreenshot interfaces.
  • Clear() method is used to clear or erase text from textbox or text area web elements.
For verifying how clear() method works to create text field, First of all we will type some text in textbox then we will get that text using getAttribute method and print it in console. Then we will clear the text and again get that text using getAttribute method and print it in console. It should return blank value.

Example of clear() method in selenium

Below given example will show you how clear method used to clear text from textbox. You can use it for text area elements as well.
package testPackage;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class ClearExample {

	public static void main(String[] args) {
		
		System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
		WebDriver driver=new ChromeDriver();
	    		
	    driver.get("http://only-testing-blog.blogspot.com/2022/11/relationship.html");
		
		//Find and locate textbox element by id.
		WebElement gp = driver.findElement(By.id("gparent_1"));
		
		//type text in it.
		gp.sendKeys("Automation");
		
		//Get value from textbox and print it in console.
		String txt = gp.getAttribute("value");
		System.out.println("Text found before clear = "+txt);
		
		//Clear textbox using clear() method.
		gp.clear();
		
		//Get value from textbox and print it in console.
		String txt1 = gp.getAttribute("value");
		System.out.println("Text found after clear = "+txt1);		
	}
}
In above given Clear() method example, We located textbox and type text "Automation" in it. Later on we printed text in console before and after clearing value from textbox.

No comments:

Post a Comment