How to highlight syntax in pre tags using highlight.js
01: <pre>
02: function name() {
03:   console.log("output")
04: }
05: </pre>
06: 
07: <script src="path/to/highlight.min.js"></script>
08: <link rel="stylesheet" href="path/to/theme.css" />
09: 
10: <script>
11:    var preTags = document.getElementsByTagName('pre');
12:    var size = preTags.length;
13:    for (var i=0; i < size; i++) { 
14:        preTags[i].innerHTML = '<code>'+preTags[i].innerHTML+'</code>'; // wrap content of pre tag in code tag
15:    }
16:     hljs.highlightAll(); // apply highlighting
17: </script>

By default highlightJS provides syntax highlighting to code engulfed in between a < code > tag.

However, you might find yourself with HTML containing code snippets that are wrapped directly in < pre > tags instead.

01: <pre>
02: function name() {
03:   console.log("output")
04: }
05: </pre>

In which case highlightJS might fail to provide proper syntax highlighting. We can fix this by dynamically wrapping the code snippets in code tags.

How to fix this.

The code shared at the beginning of this post shows you how to do that. The loop goes over every pre tag present on the page and wraps its content with the code tag.

Then calls on highlightJS once it's done to apply syntax highlighting.

Note: In the case where not all code snippets are wrapped directly in a pre tag you can add a class attribute to the specific ones you will like to modify and then fetch them using document.getElementsByClassName.

01: <pre class="code-block">
02: function name() {
03:   console.log("output")
04: }
05: </pre>
06: 
07: <script>
08:    var preTags = document.getElementsByClassName('code-block');
09:     ...
10:     hljs.highlightAll(); // apply highlighting
11: </script>