How to render code in Prismjs dynamically

I need to use Primsjs, and I want to render a code like

const a = 55

But I don’t really know how to use it in my application, I manage to show the code with the code bellow

<pre class="language-js">
<code class="language-js">
  function example(a, b) {
     console.log("example!);
  }
</code>
</pre>

But I need to upload the code inside the code block. So I try to use the Prism.highlightElement but it seems that is not working 🙁

my code

I need to know how to update the content code

>Solution :

I use it a few day ago, I have a code snippet to share to make your code works

source

In fact I used the same function as used in the https://prismjs.com/test.html#language=markup

The function is

function highlightCode() {
    var newCode = document.createElement('code');
    newCode.textContent = code.textContent;
    newCode.className = code.className;

    Prism.highlightElement(newCode);

    code.parentElement.replaceChild(newCode, code);
    code = newCode;
};

source

You need to create a new code element and inject your new code and render it with the Prism.highlightElement function, after this you just need to replace the old block with the new created just above 🙂

Leave a Reply