16

I've recently run into a problem working with selenium where calling clear() on a custom text box causes issues when entering text later in the test. The text box does check for (JavaScript) browserEvents, particularly keyDown events. I tried figuring out what clear() does to see if that could be affecting things, but I can't seem to find any specifics.

The source for the Selenium Java bindings shows that clear() does not use keyboard or mouse simulation to clear away the text from the text box. So what does it do, exactly?

Mosam Mehta
  • 1,658
  • 6
  • 25
  • 34
joshin4colours
  • 1,656
  • 4
  • 16
  • 27

2 Answers2

33

The clear() method executes an "Automation Atom", which is a JavaScript function intended to provide the smallest basic unit of automation functionality for a browser. In the case of clear(), that function sets the value property of the element to an empty string (''), then fires the onchange event on the element. The atoms function you're interested in is bot.action.clear()

DarkCygnus
  • 7,420
  • 4
  • 36
  • 59
JimEvans
  • 27,201
  • 7
  • 83
  • 108
  • Hello, I digged out this post, because I wanted to look at the source code of `WebElement.clear()`, but the links you provided are no longer active. I would be infinitely grateful if you could tell me where to look since I got stuck... – DCzo Dec 28 '17 at 10:48
  • Go to the wiki for [Automation Atoms](https://github.com/SeleniumHQ/selenium/wiki/Automation-Atoms). There is a link at the bottom that takes you to the build file. – MikeJRamsey56 Jan 31 '18 at 20:49
0

Here is what exactly clear() will do. The function will clear textbox value and enable text box. Before entering text in text field we need to clear the text field and will enable it. If we do not use clear (), we can't enter any value in text field using selenium.

driver.find_element_by_xpath(xpath).clear()
driver.find_element_by_xpath(xpath).send_keys("data")
Sanchit
  • 315
  • 2
  • 20
Kv.senthilkumar
  • 936
  • 2
  • 16
  • 29
  • 6
    This answer is not correct. You don't have to `clear()` the textbox to enable it. You would use `clear()` to clean out any existing text in the textbox before entering a new value. Jim's answer is correct and is more technically detailed. – JeffC Jul 18 '17 at 14:58