Apply Codemirror to multiple textarea by class

1.4k Views Asked by At

I'm aware that it's possible to apply codemirror to multiple textarea by Id, but unfortunately I need to use class because the textarea I'm using already have ids from other scripts.

Here's my code so far.

HTML

<textarea class="textarea-class"></textarea>
<textarea class="textarea-class"></textarea>

JS

$('.textarea-class').each(function(index, elem){
      CodeMirror.fromTextArea(elem, {
        lineWrapping: true,
        mode: "javascript",
        theme: "neat",
        lineNumbers: true,
      });
});

JSBIN

1

There are 1 best solutions below

1
On

You aren't abel to pass a jQuery element! It has to be a regular element. To solve this problem we will loop through the Array of elements from the document.querySelectorAll('.textarea-class') and pass each into the CodeMirror.fromTextarea() function.

JS

var textareas = document.querySelectorAll(".textarea-class");

for (var i = 0; i < textareas.length; i++) {
    CodeMirror.fromTextArea(textareas[i], {
        lineWrapping: true,
        mode: "javascript",
        theme: "neat",
        lineNumbers: true
     });
}

Demo with CodeMirror libraries and stylesheets: https://codepen.io/anon/pen/OvLxaG