Disclaimer:
I've blathered on kind-of excessively here in an attempt to provide enough context to pre-empt all questions you folks might have of me. Don't be scared by the length of this question: much of what I've written is very skim-able (especially the potential solutions I've come up with).
Goal:
The effect I'm hoping to achieve is displaying the same element (and all descendants) in multiple places on the same page. My current solution (see below for more detail) involves having to clone/copy and then append in all the other places I want it to appear in the DOM. What I'm asking for here is a better (more efficient) solution. I have a few ideas for potentially more efficient solutions (see below). Please judge/criticize/dismiss/augment those, or add your own more-brilliant-er solution!
"Why?" you ask?
Well, the element (and it's descendants) that I'm wanting to display more than once potentially has lots of attributes and contents - so cloning it, and appending it someplace else (sometimes more than one other place) can get to be quite a resource-hogging DOM manipulation operation.
Some context:
I can't describe the situation exactly (damn NDA's!) but essentially what I've got is a WYSIWYG html document editor. When a person is editing the DOM, I'm actually saving the "original" node and the "changed" node by wrapping them both in a div, hiding the "original" and letting the user modify the new ("changed") node to their heart's content. This way, the user can easily review the changes they've made before saving them.
Before, I'd just been letting the user navigate through the "diff divs" and temporarily unhiding the "original" node, to show the changes "inline". What I'm trying to do now is let the user see the whole "original" document, and their edited ("changed") document in a side-by-side view. And, potentially, I'd like to save the changes through multiple edit sessions, and show 'N' number of versions side-by-side simultaneously.
Current Solution:
My current solution to achieve this effect is the following:
Wrap the whole dang dom (well, except the "toolbars" and stuff that they aren't actually editing) in a div (that I'll call "pane1"), and create a new div (that I'll call "pane2"). Then deep-clone pane1's contents into pane2, and in pane1 only show the "original" nodes, and in pane2 only show the "changed" nodes (in the diff regions - everything outside of that would be displayed/hidden by a toggle switch in a toolbar). Then, repeat this for panes 3-through-N.
Problem with Current Solution:
If the document the user is editing gets super long, or contains pictures/videos (with different src attributes) or contains lots of fancy styling things (columns, tables and the like) then the DOM can potentially get very large/complex, and trying to clone and manipulate it can make the browser slow to a crawl or die (depending on the DOM's size/complexity and how many clones need to be made as well as the efficiency of the browser/the machine it's running on). If size is the issue I can certainly do things like actually remove the hidden nodes from the DOM, but that's yet more DOM manipulation operations hogging resources.
Potential Solutions:
1. Find a way to make the DOM more simple/lightweight
so that the cloning/manipulating that I'm currently doing is more efficient. (of course, I'm trying to do this as much as I can anyway, but perhaps it's all I can really do).
2. Create static representations of the versions with Canvas elements or something.
I've heard there's a trick where you can wrap HTML in an SVG element, then use that as an image source and draw it onto a canvas. I'd think that those static canvasses (canvi?) would have a much smaller memory footprint than cloned DOM nodes. And manipulating the DOM (hiding/showing the appropriate nodes), then drawing an image (rinse & repeat) should be quicker & more efficient than cloning a node and manipulating the clones. (maybe I'm wrong about that? Please tell me!)
I've tried this in a limited capacity, but wrapping my HTML in SVG messes with the way it's rendered in a couple of weird cases - perhaps I just need to message the elements a bit to get them to display properly.
3. Find some magic element
that just refers to another node and looks/acts like it without being a real clone (and therefore being somehow magically much more lightweight). Even if this meant that I couldn't manipulate this magic element separately from the node it's "referencing" (or its fake children) - in that case I could still use this for the unchanged parts, and hopefully shave off some memory usage/DOM Manipulation operations.
4. Perform some of the steps on the server side.
I do have the ability to execute server side code, so maybe it's a lot more efficient (some of my users might be on mobile or old devices) to get all ajax-y and send the relevant part of the DOM (could be the "root" of the document the user is editing, or just particularly heavy "diff divs") to the server to be cloned/manipulated, then request the server-manipulated "clones" and stick 'em in their appropriate panes/places.
5. Fake it to make it "feel" more efficient
Rather than doing these operations all in one go and making the browser wait till the operations are done to re-draw the UI, I could do the operations in "chunks" and let the browser re-render and catch a breather before doing the next chunk. This probably actually would result in more time spent, but to the casual user it might "feel" quicker (haha, silly fools...). In the end, I suppose, it is user experience that is what's most important.
Footnote:
Again, I'm NDA'd which prevents me from posting the actual code here, as much as I'd like to. I think I've thoroughly explained the situation (perhaps too thoroughly - if such a thing exists) so it shouldn't be necessary for you to see code to give me a general answer. If need be, I suppose I could write up some example code that differs enough from my company's IP and post it here. Let me know if you'd like me to do that, and I'll be happy to oblige (well, not really, but I'll do it anyway).
Take a look at CSS background elements. They allow you to display DOM nodes elsewhere/repeatedly. They are of course they are read-only, but should update live.
You may still have to come up with a lot of magic around them, but it is a similar solution to:
Create static representations of the versions with Canvas elements or something.
CSS background elements are also very experimental, so you may not get very far with them if you have to support a range of browsers.
To be honest, after reading the question I almost left thinking it belongs in the "too-hard-basket", but after some thought perhaps I have some ideas.
This is a really difficult problem and the more I think about it the more I realise that there is no real way to escape needing to clone. You're right in that you can create an SVG or Canvas but it won't look the same, though with a fair amount of effort I'm sure you can get quite close but not sure how efficient it will be. You could render the HTML server-side, take a snapshot and send the image to the client but that's definitely not scalable.
The only suggestions I can think of are as follows, sorry if they are long-winded:
How are you doing this clone? If you're going through each element and as you go through each you are creating a clone and copying the attributes one by one then this is heaavvvyy. I would strongly suggest using jQuery clone as my guess is that it's more efficient than your solution. Also, when you are making structural changes it might be useful to take advantage of jQuery's detach/remove (native JS: removeChild()) methods as this will take the element out of the DOM so you can alter it before reinserting.
I'm not sure how you'v got your WYSIWYG, but avoid using inputs as they are heavy. If you must then I'm assuming they don't look like inputs so just swap them out with another element and style (CSS) to match. Make sure you do these swaps before you reinsert the clone in to the DOM.
Don't literally put video at the time of showing the user comparisions. The last thing we want to do is inject 3rd party objects in to the page. Use an image, you only have to do it while comparing. Once again, do the swap before inserting the clone in to the DOM.
I'm assuming the cloned elements won't have javascript attached to them (if there is then remove it, less moving parts is more efficiency). However, the "changed" elements will probably have some JS events attached so perhaps remove them for the period of comparision.
Use Chrome/FF repaint/reflow tools to see how your page is working when you restructure the DOM. This is important because you could be doing some "awesome" animations that are costing you intense resources. See http://paulirish.com/2011/viewing-chromes-paint-cycle/
Use CSS over inline styling where possible as modern browsers are optimised to handle CSS documents
Can you make it so your users use a fast modern browser like Chrome? If it's internal then might be worth it.
Can you do these things in Silverlight or Adobe Air? These objects get special resource privileges, so this will most likely solve your problem (according to what I'm imagining the depth of the problem is)
This one is a bit left-field but could you open in another window? Modern browsers like Chrome will run the other window in its own process which may help.
No doubt you've probably looked in to these things more than I but good luck with it. Would be curious how you solved it.
You may also try: http://html2canvas.hertzen.com/
If it works for you canvas has way better support.
In order to get your "side-by-side" original doc and modified doc.. rather than cloning all pane1 into pane2.. could you just load the original document in an iframe next to the content you are editing? A lot less bulky?
You could tweak how the document is displayed when it's in an iframe (e.g. hide stuff outside editable content).
And maybe when you 'save' a change, write changes to the file (or a temp) and open it up in a new iframe? That might accomplish your "multiple edit sessions"... having multiple iframes displaying the document in various states.
Just thinking out loud...
(Sorry in advance if I'm missing/misunderstanding any of your goals/requirements)
I don't know if it's already the case for you but you should consider using jQuery library as it allows to perform different kinds of DOM elements manipulation such as create content and insert it into several elements at once or select an element on the page and insert it into another.
Have a look on .appendTo(), .html(), .text(), .addClass(), .css(), .attr(), .clone()
http://api.jquery.com/category/manipulation/
Sorry if I'm just pointing out something you already know or even work with but your NDA is in the way of a more accurate answer.
Related
The question is no more relevent.
I just wanted to add that if anybody encounter a need for filtering HTML, I would propose using a MutationObserver (That was my final choice ..)
Read a bit more on DOM manipulation, it will help. Yes, using content scripts here is the right way to go. You'll want to have your script run at "document_start" which is run before Chrome begins parsing the DOM (that way you'll get a head start, essentially) You could do this filtering a few ways actually;
Just use the DOM as one big string, and remove the words you want. However, this is a messy way of eoing things, if something important was named after your word (like a class, tag name, or whatnot), you'd break the DOM.
Loop over the text nodes (strings) in a DOM as soon as the DOM is ready, and replace and edit those text nodes.
There's tutorials detailing this kind of thing you can find online easily, along the lines of DOM manipulation and text node replacement. This article details it much more intimately and better than I have here: Replacing text in the DOM...solved?
And here is a JS library (from the same guy who wrote that article) which practically does all the hard work for you: https://github.com/padolsey/findAndReplaceDOMText
The way I would approach this is through a jQuery/other framework plugin. I would suggest you take a look at some highlight plugins that are available in pretty much every framework around. See here for some examples of doing highlighting.
Essentially what you'll need to do is select heading tags p tags and spans and loop over each replacing bad words.
I was wondering when to use DOM-based generation versus .innerHTML or appending strings using JQuery's .append method? I read a related post here Should you add HTML to the DOM using innerHTML or by creating new elements one by one? but I'm still unsure of the use case for each method.Is it just a matter of performance where I would always choose one over the other?
Let's say that form is an arbitrary variable:
DOM generation
var div = document.createElement("div"),
label = document.createElement("label"),
input = document.createElement("input");
div.appendChild(label);
div.appendChild(input);
form.appendChild(div);
JQuery
$(form).append("<div><label></label><input></input></div>")
The second one is more readable, although that comes from jQuery which does the innerHTML work for you. In vanilla JS, it would be like this:
form.insertAdjacentHTML("beforeend", "<div><label></label><input></input></div>");
...which I think beats even jQuery. Although, you should not worry about performance. The performance always depends on the amount of nodes to insert - for single ones, the HTML parser would be slower than creating them directly, for large HTML strings the native parser is faster than the script. If you really do worry about performance, you will need to test, test, test (and I'd say there is something wrong with your app).
Yet, there is a great difference between the two methods: With #1, you have three variables with references to the DOM elements. If you would for example like to add an event listener to the input, you can immediately do it and don't need to call a querySelector on form, which would be much slower. Of course, when inserting really many elements - with innerHTML -, you wouldn't need to do that at all because you would use delegated events for a real performance boost then.
Note that you can also shorten method #1 with jQuery to a oneliner:
var div, label, input;
$(form).append(div=$("<div/>").append(input=$("<input/>"),label=$("<label/>")));
My conclusion:
For creating only few elements the DOM approach is cleaner.
Mostly, html strings are more readable.
None of the two is faster in standard situations - benchmark results vary wide.
Personally, I don't like (direct) innerHTML for a few reasons, which are outlined well in these two answers and here as well. Also, IE has a bug on tables (see Can't set innerHTML on tbody in IE)
Generally speaking, hitting the DOM repeatedly is much slower than say swapping out a big block of HTML with innerHTML. I believe there are two reasons for this. One is reflow. The browser has to recalc for potential layout impact across potentially wide variety of elements. The other, I believe, and somebody correct me if I'm wrong, is that there's a bit of overhead involved in translating the stuff going on at the browser's post-compiled execution environment where rendering and layout state is being handled into an object you can use in JavaScript. Since the DOM is often under constantly changing conditions you have to run through the process every time with few opportunities to cache results of any kind, possibly to a degree even if you're just creating new elements without appending them (since you're likely to going to want pre-process CSS rules and things like what 'mode' the browser is in due to doctype, etc, that can be applied in a general context beforehand).
DOM methods allow you construct document fragments and create and append HTML element to those without affecting the actual document layout, which helps you avoid unnecessary reflow.
But here's where it gets weird.
Inserting new HTML into a node with nothing in it - close to a tie or something innerHTML is typically much faster at in a lot of (mostly older) browsers
Replacing a ton of HTML contents - this is actually something where DOM methods tend to win out when performance isn't too close to call.
Basically, innerHTML, if it stinks, tends to stink at the teardown process where large swaps are happening. DOM methods are better at teardown but tend to be slower at creating new HTML and injecting directly without replacing anything when there's any significant difference at all.
There are actually hybrid methods out there that can do pretty marvelous things for performance when you have the need. I used one over a year ago and was pretty impressed by response time improvement for swapping large swathes of HTML content for a lazy-loading grid vs. just using innerHTML alone. I wish I could find a link to the guy who deserves credit for figuring this out and spelling it out on the web (author, has written a lot of RegEx stuff too - couldn't google for the life of me).
As a matter of style vs perf, I think you should avoid tweaking the actual DOM node structure repeatedly but constructing HTML in a document fragment beforehand vs. using innerHTML is pretty much a matter of judgement. I personally like innerHTML for the most part because JS has a lot of powerful string methods that can rapidly convert data to HTML-ready strings. For instance:
var htmlStr = '<ul><li>' + arrayOfNames.join('</li><li>') + '</li></ul>';
That one-liner is a UL I can assign directly to innerHTML. It's almost as easy to build complete tables with the right data structure and a simple while loop. Now go build the same UL with as many LIs as the length of the arrayOfNames with the DOM API. I really can't think of a lot of good reasons to do that to yourself. innerHTML became de facto standard for a reason before it was finally adopted into the HTML 5 spec. It might not fit the node-based htmlElement object tweaking approach of the DOM API but it's powerful and helps you keep code concise and legible. What I would not likely do, however, is use innerHTML to edit and replace existing content. It's much safer to work from data, build, and swap in new HTML than it is to refer to old HTML and then start parsing innerHTML strings for attributes, etc when you have DOM manipulation methods convenient and ready for that.
Your chief performance concern should probably be to avoid hammering away at the 'live' portions of the DOM, but the rest I would leave up to people as a matter of style and testing where HTML generation is concerned. innerHTML is and has for years now been in the HTML5 working draft, however, and it is pretty consistent across modern browsers. It's also been de facto spec for years before that and was perfectly viable as an option since before Chrome was new, IMO but that's a debate that's mostly done at this point.
It is just a matter of performance. Choose the one that fits you best.
jsPerf is full of those performance test, like this one: test
All,
I'm working on an HTML page that includes a large data table.
As the user interacts with a variety of controls on that page, I'd like the data in the table to update, without reloading the page.
In other words, when the user changes the value of a control, that triggers a JavaScript function that performs a number of calculations, then "updates" the data in the table. In a typical scenario, anywhere from 50 to 500 cells would require updating.
My baseline approach:
assign each <td> cell a unique ID
in the JavaScript function, use document.getElementById() to get a reference to each cell that needs updating
use innerHTML to update those cells
This works fine, but it's probably very slow. E.g., does each call to innerHTML force the browser to re-render the entire table? In other words - does updating 500 cells trigger 500 're-renders'? Or, does the browser only re-render the table once the function is complete?
Long story short, what's the best way to do this?
My current approach?
recreate the entire table as a string in JavaScript, then use ONE call to innerHTML on the div that contains the table?
something else?
I recently watched Paul Irish's EXCELLENT (imo) presentation about optimizing JavaScript performance:
DOM, HTML5, & CSS3 Performance
In that, he describes making changes "off DOM"; unfortunately - that's mostly over my head, and his presentation doesn't include any actual code examples.
I'd prefer a straight JavaScript solution, but I'd be happy with a jQuery solution as well.
Many thanks in advance for any advice or insight.
I think using innerHTML is the way to go.
If each cell has it's own ID then the browser does not need to refresh the whole table to update a single cell.
I am using innerHTML in my current website that I am building and it works very quickly.
As long as you assign the function to the correct action that should work well.
If multiple cells will have the same value, then consider using classes,
in which case jQuery does make it easier to reference classes.
So basically, use your current approach.
Just re rendering each cell when needed is the quickest way (from my understanding and logic)
The approach you are taking is OK. However, it would be advisable to use jQuery or another abstraction library, which will take care of any quirks in the implementation of innerHtml in various browsers (some browsers are case sensitive etc.); this will make your life easier, and leave you to concentrate on developing your logic rather than working on browser idiosyncracies.
this question might be argumentative ... but I would suggest using something like jQuery jGrid plugin
it seems to me might be better that way
(excuse me if this is not the right forum to post - i couldn't find anything related to non-native programming and related to this topic)
I Am trying to set a dynamic HTML into an iFrame on the webpage. I have tried a couple of things but none of them seem to work. I m able to read the innerHTML but can't seem to update it.
// Able to read using
document.getElementById('iFrameIdentifier').innerHTML;
// On Desktop IE, this code works
document.getElementById('iFrameId').contentWindow.document.open();
document.getElementById('iFrameId').contentWindow.document.write(dynamicHTML);
document.getElementById('iFrameId').contentWindow.document.close();
Ideally the same function should work as how it works for div's but it says 'Object doesn't support this method or property".
I have also tried document.getElementById('iFrameId').document.body.innerHTML.
This apparently replaces the whole HTML of the page and not just the innerHTML.
I have tried out a couple of things and they didn't work
document.getElementById('iFrameId').body.innerHTML
document.frames[0].document.body.innerHTML
My purpose is to have a container element which can contain dynamic HTML that's set to it.
I've been using it well till now when I observed that the setting innerHTML on a div is taking increasing amount of time because of the onClicks or other JS methods that are attached to the anchors and images in the dynamic HTML. Appears the JS methods or the HTML is some how not getting cleaned up properly (memory leak?)
Also being discussed - http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_26185526.html#a32779090
I have tried a couple of things but none of them seem to work.
Welcome to IEMobile! Nothing you know about DOM scripting applies here.
Unfortunately, cross-iframe scripting does not appear to be possible in IEMobile6-7.
frameelement.contentDocument (the standard DOM method) isn't available
frameelement.contentWindow.document (the IE6-7 workaround version) isn't available
the old-school Netscape window.frames array only works for frames, not iframes
having the child document pass up its document object to the window.parent only works for frames, not iframes. In an iframe, window.parent===window.
So the only ways forward I can see are:
use frames instead of iframes. Nasty. Or,
use document.cookie to communicate between parent and child: the child document is just a script, that checks for a particular cookie in document.cookie on a poller, and when it's found that's a message from the parent, and it can write some HTML or whatever. Slow and nasty. Or,
using the server-side to inject content into the frames, passing it in as an argument to a script. Slow, nasty, and potentially insecure. Or,
avoid frames completely (best, if you can). Or,
drop support from IEMobile6-7 (best for preserving your sanity, if you can get away with it!)
Appears the JS methods or the HTML is some how not getting cleaned up properly (memory leak?)
Yes, probably. IEMobile6-7(*) is close to unusable at dynamic HTML. It gives you a lovely flavour of what scripting used to be like for us poor gits back in the Netscape 4 days.
Try to avoid creating and destroying lots of nodes and event handlers. Keep the page as static as possible, re-using element nodes where possible and setting text node data properties in preference to tearing everything down and making anew with createElement or innerHTML. Use an event stub (onclick="return this._onclick()") in the HTML together with writing to _onclick if you need to set event handlers from JavaScript, in preference to recreating the HTML with a new event handler (or just trying to set the property, which of course doesn't work in IEMobile). Avoid long-running single pages when you can.
It'll still crash, but hopefully it'll take longer.
*: that is, the versions of IE present on WinMo before version 6.1.4, where it became the infinitely better IEMobile8, marketed as “Internet Explorer Mobile 6” (thank you Microsoft).
Okay, I kinda resolved the issues that i was facing earlier and the bigger issue which was setting HTML to an iFrame on IEMobile. But i still have one more PIA which is related to double scollbars - which i am currently looking into. There seems to be more poor souls facing similar problem - if i fix that too. I will post an update here.
How did i finally write to iFrame on IEMobile?
Have 2 divs one to wrap the iFrame and the other to write inside an iFrame.
document.getElementById('OuterDiv').innerHTML = '';
document.getElementById('OuterDiv').innerHTML = '<iframe id="iFrameId" src="somefile.html"></iframe>';
This creates an iFrame each time and in the somefile.html on load there is a InnerDiv.innerHTML which doesn't seem to leak the memory.
In the somefile.html there will be an onLoad method which will fetch the HTML (explained below on how i managed to get it) and do a
document.getElementById('InnerDiv').innerHTML = dynamicHTML;
How did I manage to pass the HTML between parent and child iFrame
As well explained by #bobince earlier, one has to rely on 3rd party service like a cookie or a server to pass around the data between parent and the child iFrame.
I infact used an ActiveXControl to set and get data from the parent and child iFrame's javascript respectively. I won't recommend doing this if you have to introduce an ActiveX Control just for this. I accidentally already have one which I use to get the Dynamic HTML in the first place.
If you need any help you can DM me - Twitter #Swaroop
Thanks #bobince for your help. I am marking this one as an answer because it says what i did to fix the issue.
The things I'm trying to get my website to do are getting fairly complex, some of the things that need to be done take long enough that it gives visible delays.
Mainly, adding content to the document slows things down as well as jquery animations that I'm using.
I create elements using document.createElement("div") rather than just doing document.write("<div id='someId'></div>"), and the animations are the custom animation using .animation();
I'm wondering how I can continue to add content as I am but prevent the browser from freezing every time I want to add something.
Any suggestions for speeding things up so there is less of a delay?
Tips on what to avoid in javascript programming that gives increased delay would be really helpful.
This sounds more like you want to improve the DOM interaction performance rather than javascript, so in that vein:
Yes, document.write is bad, it blocks additional loading (any JS executing before your pages has finished loading basically requires all other processing to stop -- modern browsers like Safari (and by proxy Chrome) and Firefox do a degree of content preloading in order to prevents loads from blocking but subsequent style resolution, etc is largely blocked.
document.createElement is in general the best solution, although their are certain cases where just manipulating innerHTML on an element may be faster -- but that is not yet cross browser compatible (i think innerHTML doesn't exist till Firefox 3.5) and the perform characteristics are tricky.
Reduce the amount of content you load initially -- eg. if you have lots of content (or content that requires large scripts) attempt to delay loading until after the initial page load has completed.
Oh, for animations you should look at CSS animations and they perform much better than any JS implementations, but they're only present in Safari (and by proxy Chrome) and Firefox 3.5 -- definitely not in IE :-(
In terms of JavaScript performance, avoid with and getters/setters like the plague and you should be fine in most modern JS implementations.
I know this is a couple of years late but better late than never considering this question popped up at the top of google's list for javascript animation optimization.
If you need to add a large amount of elements to the DOM and don't want to use innerHTML to do so you can speed that up I believe by adding the elements to a documentFragment first and then injecting the documentFragment all at once into the DOM. I remember reading that DOM injection is the slowest part of using the standard API to create and add elements. documentFragment allows you to inject all of its contents into the DOM in one go eliminating a large amount of overhead caused by calling appendChild or other insertion methods multiple times. appendChild and other insertion methods supposedly don't suffer the same costs when inserting into a documentFragment opposed to inserting into the DOM. I wish I could find the article I read this in as it had some really nice benchmark tests and explanations. I'm sure you can find more information by doing some searches.
As always though which method to use should be determined by testing on a case by case basis. Eventually you'd probably learn which one to use based on structure of the elements, amount, and use.
PS. There may be an issue with styles and documentFragment but I can't remember what was said about them, either way it'd be something worth checking out.
JQuery is great for manipulating the DOM. I'd take a look at their code in order to get some ideas. Or, seeing how I'm way lazy, I'd just use their stuff.
In one of the podcasts Jeff Atwood mentioned you'd have to be crazy to write your own javascript... after using JQuery, I'd have to agree with him.
Although I am a huge fan of jQuery, and it makes development much easier, note that a jQuery statement (or in any JavaScript library) will never be as fast as its semantic equivalent in plain JavaScript because of the extra overhead.
That being said, these are my goto references whenever I want to speed up my JavaScript.
http://home.earthlink.net/~kendrasg/info/js_opt/
http://www.miislita.com/searchito/javascript-optimization.html
There is document fragment function which can make life much more easier. Here is the example use.
function appendDivs(element){
var fragment = document.createDocumentFragment();
for(var i=0;i<10;i++){
var div = document.createElement("div");
fragment.appendChild(div);
}
element.appendChild(fragment);
}
For a complete reference, you can see this post on my blog.
What surprises most people is that using innerHTML is, actually, the fastest way there is to manipulate the DOM.
You can see one benchmark here for example.
// Some functions for easier coding in DOM
function createEl(el){
return document.createElement(el);
}
function addElBody(el){
return document.body.appendChild(el);
}
function addElChild(el, child){ //el- parent
return el.appendChild(child);
}
// Example :
var container=createEl('div');
container.setAttribute('id', 'container');
addElBody(container);
var item=createEl('ul');
item.setAttribute('id', 'list');
addElBody(item);
addElChild(container, item);