How to Re-Run Prism.js on AJAX Content

• 1 min read • 3 votes

This post was last updated Jan 7, 2013 and may be out of date

Prism.js is a great library to handle syntax highlighting for code blocks on a web page. However, since Prism runs automatically after being embedded (hence why you need to include it at the bottom of the HTML) content that is loaded later is not highlighted. After console logging the Prism object in Chrome developer tools I discovered a method called highlightAll() which can be used to force Prism to rerun on the current page.

// Rerun Prism syntax highlighting on the current page
Prism.highlightAll();

If you don’t want Prism rescanning the entire DOM you can selectively highlight elements with the highlightElement() function.

// Say you have a code block like this
/**
  <pre>
    <code id="some-code" class="language-javascript">
      // This is some random code
      var foo = "bar"
    </code>
  </pre>
*/

// Be sure to select the inner <code> and not the <pre>

// Using plain Javascript
var block = document.getElementById('some-code')
Prism.highlightElement(block);

// Using JQuery
Prism.highlightElement($('#some-code')[0]);

It’s as simple as that! I’m not sure why Prism doesn’t include this tip on the website.

Edit: The Prism folks tweeted me a link to the documentation on this: prismjs.com/extending.html#api

Now look what you've done 🌋
Stop clicking and run for your life! 😱
Uh oh, I don't think the system can't handle it! 🔥
Stop it, you're too kind 😄
Thanks for the love! ❤️
Thanks, glad you enjoyed it! Care to share?
HN Reddit

More Posts ✍🏻

See All »
• 6 min read • 80 votes
👆🏻 Creating a Pure CSS Dropdown Using the :hove...
Read Post »
• 4 min read • 1545 votes
💻 Wait for User to Stop Typing, in JavaScript
Read Post »
• 4 min read • 3814 votes
😈 Productive Procrastination
Read Post »
• 3 min read • 246 votes
✨ HTML Share Buttons
Read Post »
• 8 min read • 339 votes
🚜 A Simple Web Scraper in Go
Read Post »
• 6 min read • 86 votes
👔 Quit With Positivity
Read Post »
• 5 min read • 404 votes
🚀 Getting Over the Fear of Launching
Read Post »

Be the first to hear about posts, right in your inbox 💌