Search code examples
clojurescriptom

How to turn text into DOM elements using Clojurescript? (And Om?)


In a ClojureScript/Om app, I have a DOM and a string of HTML.

How can I translate that string of HTML into elements I can insert into the DOM?

I've started down the path of parsing the HTML with hickory, planning to then process the hickory data to create DOM elements, but I think there must be a simpler way I'm overlooking.

(I don't need to validate the HTML, I can assume it's safe and valid enough.)


Solution

  • You don't need to parse the HTML string. It's unnecessary overhead. React/Om supports something like DOM's innerHTML property. Just set the prop this way:

    (om.dom/div #js {:dangerouslySetInnerHTML #js {:__html "<b>Bold!</b>"}} nil)
    

    If you work with plain DOM without Om, set the innerHTML property like:

    (let [div (. js/document getElementById "elId")]
         (set! (. div -innerHTML) "<b>Bold!</b>"))