简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM