Programmatically edit CodeMirror contents without access to object

The wrapping div DOM element (with class CodeMirror) will have a property CodeMirror that refers to the editor instance object. You can call setValue on that.


The answers posted by others are correct, but if instead of replacing codemirror's value, you want to send keyboard events then you can do something like this:

/* getting codemirror element */
WebElement codeMirror = driver.findElement(By.className("CodeMirror"));

/* getting the first line of code inside codemirror and clicking it to bring it in focus */
WebElement codeLine = codeMirror.findElements(By.className("CodeMirror-line")).get(0);
codeLine.click();

/* sending keystokes to textarea once codemirror is in focus */
WebElement txtbx = codeMirror.findElement(By.cssSelector("textarea"));
txtbx.sendKeys("Hello World");

For selenium to detect the keyboard events, you'll first have to bring codemirror into focus.


@user3233451 - in my case I had to reference the correct web element for example: By.cssSelector(".CodeMirror").

Additonally, I had two CodeMirror web elements on the page, hence I did the following:

    //declare codemirror variable
    private By codeMirrorWebElement = By.cssselector(".CodeMirror");

    //use Javascript executor to access each code mirror element via its respective index
    ((JavascriptExecutor) driver).executeScript("arguments[0].CodeMirror.setValue( '"+ query1 + "');", driver.findElements(codeMirrorWebElement).get(0));
    ((JavascriptExecutor) driver).executeScript("arguments[0].CodeMirror.setValue( '"+ query1 + "');", driver.findElements(codeMirrorWebElement).get(1));

Posting this here since the chosen answer helped me out, but I lacked some information to completely solve my problem (mostly due to me not knowing JavaScript or how to interact with WebElement properties). This is how the code would look like for Selenium/Java:

WebDriver driver = new FirefoxDriver();
WebElement queryInput = driver.findElement(By.cssSelector("div[class='CodeMirror']"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].CodeMirror.setValue(\"" + query + "\");", queryInput);