Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 863
Vianne Avatar asked Aug 13 '26 14:08

Vianne


1 Answers

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

like image 65
Philipp Avatar answered Aug 15 '26 09:08

Philipp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!