Skip to content

Syntax highlight any block on a Web Page

New Course Coming Soon:

Get Really Good at Git

I had the need to add syntax highlighting to a page, but I didn’t have the luxury of changing the markup.

Most syntax highlighting libraries, like Prism.js, force you to use a fixed structure like this:

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

Citing this:

Prism does its best to encourage good authoring practices. Therefore, it only works with elements, since marking up code without a element is semantically invalid.

It’s all nice and idealistic and all but I had my code in a div from an outside source. You force me that markup, but I don’t have that.

I finally found https://highlightjs.org/ that lets me apply syntax highlighting to any element I want on the page, by loading the library first and then calling:

document.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('.my-code-div').forEach((el) => {
    hljs.highlightElement(el)
  })
})
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!

Here is how can I help you: