/

Syntax Highlighting for Any Web Page Element

Syntax Highlighting for Any Web Page Element

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:

1
2
3
4
5
<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:

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

tags: [“syntax highlighting”, “web development”, “highlight.js”]