How to reapply prettyPrint AFTER run_prettify.js loaded

I am trying to use a Javascript code prefix and ask a question.

If I do not assign class="prettyprint" to <pre> in static html, but you want to apply printprint later (for example, when the user clicks the colorize button on my web page) , how can I achieve this

It's pretty easy to modify the source file run_prettify.js or prettify.js because I'm going to use it offline.

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, raise the console, do:

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

The syntax color does not appear.

enter image description here

+4
source share
2 answers

According to the comment found here, How to get a fingerprint for working with a dynamically created dom element , I find a way out. Just call:

 PR.prettyPrint() 

BTW: If you want to remove code color highlighting, you cannot just set the pre class to empty and then PR.prettyPrint() again. PR.prettyPrint() can only attach color tags, but not remove them. A possible way to do this is to save the original <pre> content before applying prettyprint, and then restore the <pre> content later. Checked in my jQuery post how to clone saved items? .

enter image description here

+9
source

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'); 
0
source

All Articles