Home  >  Q&A  >  body text

How to highlight newly generated code blocks with highlight.js - javascript -

For example, segmentfault editor. . . . .

The code block is not highlighted, the content found by Baidu

hljs.initHighlightingOnLoad();
Rendering is executed during onload, that is to say, any changes to the document after that will not be executed. So obviously this cannot highlight the code of the document retrieved from the interface.

Note that I am talking about newly generated content, code highlighting is invalid, only pre code, no class. . .

怪我咯怪我咯2636 days ago967

reply all(1)I'll reply

  • 怪我咯

    怪我咯2017-07-05 10:44:48

    There is more than one way to highlight code. hljs.initHighlightingOnLoad() just binds the highlighting operation to the document loading event.

    hljs.initHighlightingOnLoad()Code:

    function h(){addEventListener("DOMContentLoaded",_,!1),addEventListener("load",_,!1)}

    You can see the official documentation of HLJS:
    https://highlightjs.org/usage/

    There is a code example in the Custom Initialization section:
    Example 1:

    $(document).ready(function() {
        $('pre code').each(function(i, block) {
            hljs.highlightBlock(block);
        });
    });

    Example 2

    hljs.configure({useBR: true});
    
    $('p.code').each(function(i, block) {
        hljs.highlightBlock(block);
    });

    So, if you only need to highlight a single area, just

    hljs.configure({ ... });
    hljs.highlightBlock($('....'));

    Language-related configuration is configured through .configure. For configuration items, please refer to: http://highlightjs.readthedoc...

    reply
    0
  • Cancelreply