When I needed to add syntax highlighting to a web page, I encountered the challenge of not being able to change the page’s markup. Many syntax highlighting libraries, such as Prism.js, require a specific structure like the following:

<pre>
 <code class="language-js">
 ...
 </code>
</pre>

Quoting Prism.js documentation:

Prism encourages good authoring practices and only works with <pre> elements as marking up code without a <pre> element is semantically invalid.

While this is commendable, I had my code inside a <div> from an external source. I was constrained by the required markup, but I didn’t have access to that.

Finally, I discovered highlight.js, a library that allows me to apply syntax highlighting to any element on the page. To achieve this, I first load the library and then call the following code:

document.addEventListener('DOMContentLoaded', () => {
 document.querySelectorAll('.my-code-div').forEach((el) => {
 hljs.highlightElement(el)
 })
})