How to call highlight.js after DOM change in Elm

Hi - I have an elm app that uses elm-explorations/markdown to render markdown into HTML. That markdown might contain code blocks that I’d like to highlight using Highlight.js. I think I need to trigger the highlightAll() method of Highlight.js whenever the DOM changes and new code blocks appear, but I’m not sure how best to do so. I’d really appreciate advice!

you can use ports to communicate with JS or you can use elm-syntax-highlight → this is used by elm pages

You could possibly use custom elements too. Have a custom element that wraps Highlight.js and knows when to call highlightElement() on itself. Not sure if this would be better or worse than the ports approach though.

We actually do something similar to this at work, though not in Elm the approach would be the same. We have a framework specific component that we pass the code to and inside that component we use Highlight.js to generate the highlighted code and then set that as the child. For Elm you’d have something like

Html.node "code-highlight"
    [ Html.Attributes.attribute "code" youCodeAsAString ]

and in your custom element you’d have something roughly like

customElements.define("code-highlight", class extends HTMLElement {
  attributeChangedCallback(name, oldValue, newValue) {
    if (name === "code" && oldValue !== newValue) {
      // use Highlight.js here to generate highlighted code

There’s definitely a little more to setting up your custom element but that’s roughly what would be needed. You’d also probably want some other attributes or properties for setting which language you want to hightlight.


An mvp in Ellie Definitely needs some refinement :sweat_smile:


An update to the above Ellie that includes actual highlighting and a little more code being highlighted.


In a recent project I had the same issue. I tried to re-apply the syntax hilighter using ports but this caused the app to crash as it is modifing the DOM.

My solution has been to use dillonkearns/elm-markdown and pablohirafuji/elm-syntax-highlight, so now everything is 100% Elm and is working out of the box.

You can see the code here: elm-exercises/Markdown.elm at master · lucamug/elm-exercises · GitHub (still messy)


This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.