How to re-apply prettyPrint AFTER run_prettify.js has been loaded
Asked Answered
K

2

7

I'm trying with Javascript code prettifier, and come up with a question.

If I do not assign class="prettyprint" to <pre> in static html, but wish to apply prettyprint later(e.g, when user click on a "colorize" button on my webpage), how can I achieve this?

Slightly modifying original run_prettify.js or prettify.js is acceptable, because I'm going to put this to offline use.

My experiment:

Writing try-delay-class.html:

<html>
<head>
<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script>
</head>
See it:
<pre>
class Voila {
public:
  // Voila
  static const string VOILA = "Voila";

  // will not interfere with embedded <a href="#voila1">tags</a>.
}
</pre>
</html>

Open in Chrome v26, bring up the console, execute:

pres=document.getElementsByTagName('pre')
pres[0].className+=" prettyprint"

Syntax color does not come up.

enter image description here

Kallman answered 21/4, 2013 at 1:17 Comment(0)
K
13

According to a comment found here, How to get prettyprint to work on dynamically generated dom element , I find the way out. Just call:

PR.prettyPrint()

BTW: If you want to remove code color highlight, you cannot simply set pre's class to empty followed by PR.prettyPrint() again. PR.prettyPrint() can only attach color tags but not remove them. A feasible way to do that is saving your original <pre> content before applying prettyprint, then restore <pre>s content later. Verified in my post jQuery, how to clone back saved elements? .

enter image description here

Kallman answered 23/4, 2013 at 3:4 Comment(1)
When PR.prettyPrint() is run, it adds the "prettyprinted" class to each element it changes. If you need to reapply prettyPrint to a <pre>, remove the "prettyprinted" class first, then call PR.prettyPrint()Sharpeyed
E
1

You can find three examples here

I did it as follows in js:

document.getElementById('outputa').innerHTML = 
 PR.prettyPrintOne("your code in brackets or your variable (without these brackets)",
 'java');
Either answered 12/11, 2017 at 9:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.