Vianne
Vianne

Reputation: 578

Apply Codemirror to multiple textarea by class

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

Upvotes: 3

Views: 1487

Answers (1)

Philipp
Philipp

Reputation: 475

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

Upvotes: 2

Related Questions