Clearing a Text Field and Focusing On a Control

Learn how to clear and assert a text field using Selenium.

Clear a text field

Clearing out a text field is important, as calling out the sendKeys() function to an already filled text field will only concatenate the new text with the old. So, it is advisable to clear a text field before sending new keys to it.

driver.findElement(By.name("username")).sendKeys("test");
driver.findElement(By.name("username")).sendKeys(" wisely"); 
// now => 'test wisely'
driver.findElement(By.name("username")).clear();
driver.findElement(By.name("username")).sendKeys("agileway");

Assert a value

We can also assert the value of a text field by:

driver.findElement(By.id( "user")).sendKeys("testwisely");
driver.findElement(By.id("user")).getAttribute("value").then(function(value){
  assert.equal("testwisely", value);		
});

Get hands-on with 1200+ tech skills courses.