To append an html element (including all child elements) to the end of the of the pages body, we could do this simply with:
document.body.innerHTML+="<div id=’newElement’>sample text</div>";
...but this forces the browser to re-render the entire page, which is not usually an issue, unless the page also contains any flash objects, because flash objects are restarted.
To stop this, we can use the createElement() function. As createElement requires you to define the object tag, we can use it to create a temporary div element, which can be used as a holding area for our created elements.
hiddenArea=document.createElement("div");
hiddenArea.style.display="none";
hiddenArea.ID="ParseArea";
Now we have created a hidden div element with an id of “ParseArea”. Into this div element we can now safely insert our html.
hiddenArea.innerHTML=theHTML;
The html elements are now rendered to the page, but in our holding pen. We must now transfer them as elements from ParseArea to our destination element.
for (c=0;c<hiddenArea.childNodes.length;c++) {
destinationObj.appendChild(hiddenArea.childNodes[c]);
}
This will now safely paste any html into your page, without any side-effects. Place this code into a function, such as:
function pasteRawHTML(theHTML,destinationObj) {
var hiddenArea=null;
if (document.getElementById("ParseArea")==null) {
hiddenArea=document.createElement("div");
hiddenArea.style.display="none";
hiddenArea.ID="ParseArea";
}else {
hiddenArea = document.getElementById("ParseArea");
}
hiddenArea.innerHTML=theHTML;
hiddenArea.innerHTML="";
}
So in normal operation, we can now easily append html onto the end of the body, by calling:
pasteRawHTML("<div id=’newElement’>sample text</div>",document.body);