javascripthtmlcsshighlight.js

highlight.js: CSS styling absent after setting innerHTML


I am using highlight.js for syntax highlighting in a webpage.

When I change the content by setting the relevant innerHTML using JavaScript, the content output on the page updates as expected. However the changed content is not highlighted in the browser.

What is the correct way to deal with this situation, generally or with highlight.js using only JavaScript, HTML and CSS?


Solution

  • I found a solution thanks to @Afsar's insightful comment.

    The function initHighlighting from highlight.js:

    initHighlighting()

    Applies highlighting to all <pre><code>...</code></pre> blocks on a page.

    ... contains an internal check to see whether it has already been run. Since I was attempting to run it more than once, highlighting was not working correctly.

    So one possible solution to updating highlighting after updating content via JavaScript with no page reload is:

    var element = document.querySelector(".class_that_contains_code_blocks");
    var blocks = element.querySelectorAll('pre code');
    blocks.forEach(hljs.highlightBlock);