Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

configuration of highlight.js for non-pre container

I want to use highlight.js in my websie. But it defaults works with <pre><code></code></pre> blocks. I like to use just <code></code>(actually in <div><code>) and use the configuration of official website. But it does not work.

the configuration is as following:

hljs.configure({useBR: true});
$('div.code').each(function(i, e) {hljs.highlightBlock(e)});
like image 704
liu Avatar asked Sep 20 '25 02:09

liu


1 Answers

I was just dealing with this right now, might as well add it here. My exact issue was highlighting both the block <pre><code></code></pre> and the inline <code></code>, which is very similar. Note that I used it for the <code> tag name the exact code is this.

In place of:

hljs.initHighlightingOnLoad();

Use (replace 'code' on the first line with your selector)

document.querySelectorAll('code').forEach((block) => {
    hljs.highlightBlock(block);
});

However, if there's no <pre></pre>, you'll want to use another configuration option, like the useBr: true in front of your selector block. You'll have to use <br> to signal line breaks then, of course.

hljs.configure({useBR: true});

document.querySelectorAll('code').forEach((block) => {
    hljs.highlightBlock(block);
});

One thing to note. If someone's issue is the same as mine (both pre and no-pre), you don't need this option, as the inline code won't contain breaks and the block one is already within the <pre>

like image 88
Morgosus Avatar answered Sep 22 '25 15:09

Morgosus