Prabu
Prabu

Reputation: 3728

Selenium - Enter a text using java script

Insert a value in a particular element by using javascript

Html code

<div class="CodeMirror-code" style="">
<div style="position: relative;">
<div style="position: absolute; left: -52px;">
    <div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 18px; width: 12px;">1</div>
</div>
<pre>
    <span class="cm-word"></span>
</pre>
</div>
</div>

I need to insert a text in the span class <span class="cm-word"></span>

Code:

WebDriver driver = DriverFactory.getWebDriver()
WebElement webElement = driver.findElement(By.xpath("//div[@class='CodeMirror-code']//pre"))
JavascriptExecutor executor = ((driver) as JavascriptExecutor)
executor.executeScript("arguments[0].value='sample text';", webElement)

When I execute the code value was not inserted and I'm not getting any error. Normal setText method not working, so that I choose the javascript option.

This is a salesforce application console mode execution

Upvotes: 1

Views: 450

Answers (1)

Greg Burghardt
Greg Burghardt

Reputation: 18783

Use the innerHTML property instead:

executor.executeScript("arguments[0].innerHTML = 'sample text';", webElement)

Alternatives:

  • textContent: arguments[0].textContent = 'sample text'
  • innerText: arguments[0].innerText = 'sample text'

The value property is used for form fields that allow user input.

Upvotes: 1

Related Questions