Get CodeMirror instance

Another method I have found elsewhere is as follows:

//Get a reference to the CodeMirror editor
var editor = document.querySelector('.CodeMirror').CodeMirror;

This works well when you are creating the CodeMirror instance dynamically or replacing an existing DOM element with a CodeMirror instance.


You can find the instance starting with the <textarea> and moving to the next sibling.

Native

  • Functional

    document.querySelector('#code').nextSibling,
    
  • Selector

    document.querySelector('#code + .CodeMirror'),
    

jQuery

  • Functional

    $('#code').next('.CodeMirror').get(0),
    
  • Selector

    $('#code + .CodeMirror').get(0)
    

Extra: A more advanced solution involving clipboard.js -> JSFiddle Demo


Example

// Selector for textarea
var selector = '#code';

$(function() {
  var editor = CodeMirror.fromTextArea($(selector).get(0), {
    mode: 'javascript',
    theme: 'paraiso-dark',
    lineNumbers : true
  });
  editor.setSize(320, 240);
  editor.getDoc().setValue(JSON.stringify(getSampleData(), null, 4));
  
  $('#response').text(allEqual([
    document.querySelector(selector).nextSibling,        // Native - Functional
    document.querySelector(selector + ' + .CodeMirror'), // Native - Selector
    $(selector).next('.CodeMirror').get(0),              // jQuery - Functional
    $(selector + ' + .CodeMirror').get(0)                // jQuery - Selector
  ]));
});

function allEqual(arr) {
  return arr.every(function(current, index, all) {
    return current === all[(index + 1) % all.length];
  });
};

// Return sample JSON data.
function getSampleData() {
	return [
        { color: "red",     value: "#f00" },
        { color: "green",   value: "#0f0" },
        { color: "blue",    value: "#00f" }
    ];
}
#response { font-weight: bold; }
<link href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.7.0/codemirror.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.7.0/theme/paraiso-dark.min.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.7.0/codemirror.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div>All equal?: <span id="response"></span></div>
<textarea rows="10" cols="60" id="code"></textarea>

Someone just posted an answer but removed it. Nevertheless, it was a working solution. Thanks!

-- Basically this was his solution:

// create an instance
var editor = CodeMirror.fromTextArea('code');
// store it
$('#code').data('CodeMirrorInstance', editor);
// get it
var myInstance = $('code').data('CodeMirrorInstance');
// from here on the API functions are available to 'myInstance' again.

There is a getWrapperElement on code mirror editor objects which gives you the root DOM element of the code mirror instance:

var codemirrorDomElem = editor.getWrapperElement();