Created
September 3, 2017 20:25
-
-
Save jochemstoel/535fafd78b78f79d289a35f51843f623 to your computer and use it in GitHub Desktop.
Iterate all <code> elements and render CodeMirror on them using jQuery. (useful for markdown rendered as HTML)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* store instances in property for later access | |
* that way you can do CodeMirror.rendered[2].getValue() | |
*/ | |
CodeMirror.rendered = [] | |
$(document).ready(function() { | |
$('code').each(function() { /* iterate <code> nodes */ | |
let innerText = $(this).text() /* save its content */ | |
/* in properly used markdown, codes are inside <pre> */ | |
let pre = $(this).parent() | |
pre.text('') | |
/* clear the pre node and render CodeMirror on it */ | |
CodeMirror.rendered.push( | |
myCodeMirror = CodeMirror(pre[0], { | |
/* you could technically get the "lang" attribute */ | |
mode: 'javascript', | |
theme: 'monokai', | |
value: innerText, /* we saved this earlier */ | |
readOnly: true /* if you only want to highlight */ | |
}) | |
) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment