I am still trying to create a full DOM document from a string. I got a bunch of interesting suggestions on this other question, but none actually fits what I’m looking for. So I’m trying to understand how things work to maybe find a solution.
We need to replace a lot of JQuery code with ‘native’ Javascript. With Jquery, we are able to do $('<html><head>...</head><body>...</body></html>') and then perform operations on the nodes of this object, search them… etc.
What does Jquery do? Does it create a new document? Append to the existing one?
Since a lot of people question our replacement of Jquery, here is a little more details: we are building a chrome application which will make use of content script. Even if Jquery is lightweight, it’s not very kind of us to add a couple MB of memory consumed in each tab for a very few Jquery methods. Jquery is awesome and fits many many needs, not ours.
You can find your answer in the jQuery source. You start out with
core.js, where you’ll find theinitmethod. If you follow the logic there, you’ll see that for any nontrivial elements it’ll calljQuery.buildFragment, which indeed builds aDocumentFragmentwhich it’ll populate with the content you specified. That will teach you how to deal with building a DOM tree from a string, including stripping out various bits of content that you most likely won’t want.