Blog of Raivo Laanemets

Stories about web development, freelancing and personal computers.

Blog upgrade: highlight.js

I have upgraded the blog to highlight source code snippets using the highlight.js library. I had one issue during the upgrade. My Markdown parser uses data-language attribute for storing the snippet language but highlight.js expects just a class attribute. I'm using the custom initialization code to mitigate the issue:

if (window.addEventListener && document.querySelectorAll) {
    window.addEventListener('load', function() {
        var snippets = document.querySelectorAll('pre code');
        for (var i = 0; i < snippets.length; i++) {
            var snippet = snippets.item(i);
            var language = snippet.getAttribute('data-language');
            if (language) {
                snippet.className = language;
    }, false);

The code only works on browsers IE9 or newer (99+% of my readers). I'm setting the class before applying highlighting using the hljs.highlightBlock(snippet) method call. It would have been nice if the method accepted language as an option but works this way too. Unsurprisingly, it was already reported as in issue.


No comments have been added so far.

Email is not displayed anywhere.
URLs (max 3) starting with http:// or https:// can be used. Use @Name to mention someone.