Skip to content

Instantly share code, notes, and snippets.

@jochemstoel
Created September 3, 2017 20:25
Show Gist options
  • Save jochemstoel/535fafd78b78f79d289a35f51843f623 to your computer and use it in GitHub Desktop.
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)
/* 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