Last updated 2022-07-26 06:15:02

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="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/highlight.min.js"></script> 08: 09: <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlightjs-themes@1.0.0/androidstudio.css" /> 10: 11: <script> 12: var preTags = document.getElementsByTagName('pre'); 13: var size = preTags.length; 14: for (var i=0; i < size; i++) { 15: preTags[i].innerHTML = '<code>'+preTags[i].innerHTML+'</code>'; // wrap content of pre tag in code tag 16: } 17: hljs.highlightAll(); // apply highlighting 18: </script>

You can find HighlightJS CDN links here [β†—] and themes here [β†—].

By default highlightJS [β†—] provides syntax highlighting to code engulfed 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 this 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>

Here is another article you might like 😊 "Diary Of Insights: A Documentation Of My Discoveries"