Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 🙁

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading