How to make printprint work with dynamically generated dom element

I use the prettyprint plugin as a syntax shortcut, it works fine when the page loads, but when I add new elements dynamically, it does not work! I tried using prettyPrint() to call it after loading the new content, but it will not work! I also followed the instructions on the plugins website, wrapping prettyPrint() with a function, but it didn't work either! Any help is appreciated. I installed the plugin as follows:

 <script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script> 

my code is:

 function showCode(e){ (e.preventDefault) ? e.preventDefault() : e.returnValue = false; var parent = document.createElement('div'), pre = document.createElement('pre'), code = document.createElement('code'), elm = (e.currentTarget) ? e.currentTarget : e.srcElement, src = elm.getAttribute('href'), id = elm.getElementsByTagName('img')[0].getAttribute('src').replace(/images\/(.+?)\.png/g, "$1"); parent.id = "codeZoom"; pre.className = "prettyprint linenums lang-" + id; var xhr = (window.XMLHttpRequest) ? new window.XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP"); xhr.open('get', src, true); xhr.send(); xhr.onreadystatechange = function() { if(xhr.readyState == 4 && xhr.status == 200) { var text = document.createTextNode(xhr.responseText); code.appendChild(text); pre.appendChild(code); parent.appendChild(pre); document.getElementsByTagName('body')[0].appendChild(parent); center(parent); prettyPrint(); } } } 

I am currently getting a prettyPrint error message undefined.

+7
source share
2 answers

As far as I can tell, your code seems to be correct.

1) include a fairly printed version (not run_xxx)

2) calling prettyPrint () anytime your Dom is updated

However, your script, which includes prettyPrint, is missing the closure, "so maybe it's just a typo of your problem :)

+7
source

When prettyprint () is executed, it adds the "prettyprinted" class to the container element. I guess its not very printed twice, probably breaking things.

You just need to remove this class before running prettyprint () again.

 $('#my_element').removeClass('prettyprinted'); prettyPrint(); 
+6
source

All Articles