Juri Strumpflohner
Juri Strumpflohner Juri is a full stack developer and tech lead with a special passion for the web and frontend development. He creates online videos for Egghead.io, writes articles on his blog and for tech magazines, speaks at conferences and holds training workshops. Juri is also a recognized Google Developer Expert in Web Technologies

Create DOM Tree out of a Dynamic HTML String

1 min read

Just a very short post before I go to bed as I'm really tired today. I just played around with some JavaScript code, building a Google Chrome extension when I came to the point where I needed to process the DOM tree of a HTML string.

Basically I had something like the following:
...
var dynamicHtmlString = "<pre>public class SomeClass{....}</pre>";
...
The dynamicHtmlString was build by my JavaScript code through a long-lasting process. At the end I wanted to format those (basically pieces of source code) in a proper way by associating the "prettyprint" css class to all "pre" elements and then calling google-code-prettify's prettyPrint() method.

Simply doing document.body.innerHTML=dynamicHtmlString; doesn't work obviously as I wanted to use jQuery for traversing the DOM and adding the CSS class. Luckly, jQuery does also support creating the DOM tree, by simply wrapping html code within $().
   var dynamicHtmlString = "<pre>public class SomeClass{....}</pre>";
$(dynamicHtmlString).appendTo("body");

$("pre").each(function(){
$(this).attr("class", "prettyprint"); //check this for compatibility with v1.6 -> use .prop(...) otherwise
});
prettyPrint();
So that did the job. Pretty easy, isn't it :). This tells a lot about the power of jQuery. Love this library!
Questions? Thoughts? Hit me up on Twitter
comments powered by Disqus