Clearing the contents of a DOM Element
Sometimes we get lazy, we decide not to care about a couple of K of our user's RAM and we do silly things like replacing the content of a DOM Element with innerHTML. It's not a huge deal, in fact I'm a fan of using the AHAH method of inject pre-formatted XHTML into my document when memory consumption is small or not an issue. AHAH is easy. You can take advantage of all the fancy parsing resources you have with with serverside development, expose no actual data to the client. It's quick and dirty, and that's often times ok. Thing is, when you are writing an application that may ping a webservice and update content on a regular basis (whether it's an AIR application or just something that runs in a browser) it's not cheap. Since you can't have quick, cheap and dirty, you end up paying for the repeted injection of chunks and use of innerHTML through memory loss, and browser performance suffers.
-
var Someobject = {
-
clearElement : function(el){
-
if (!el) return false;
-
var el = (typeof el === 'string') ? document.getElementById(el) : el;
-
var i = 0;
-
while (el.hasChildNodes())
-
{
-
el.removeChild(el.firstChild);
-
}
-
delete el;
-
return true;
-
}
-
};
Make sure you know what you're removing
If you're not using firebug or firebug lite, or a webkit nightly. You might want to be able to generate console-like output to give you a clue as to what elements you're actually removing from the DOM. If that's the case, you can just add something like this trace function to SomeObject.
-
var Someobject = {
-
trace : function(str){
-
if (window.console) {
-
return console.log(str);
-
} else {
-
if (!document.getElementById("clearElementOutput")){
-
var output = document.createElement("div");
-
output.id = "clearElementOutput";
-
document["body"].appendChild(output);
-
}
-
// dirty
-
document.getElementById("clearElementOutput").innerHTML += str + "<br />";
-
return true;
-
}
-
-
},
-
clearElement : function(el){
-
if (!el) return false;
-
var el = (typeof el === 'string') ? document.getElementById(el) : el;
-
var i = 0;
-
while (el.hasChildNodes())
-
{
-
//comment this out to suppress output
-
this.trace(i++ + "deleting " + el.firstChild.nodeName);
-
el.removeChild(el.firstChild);
-
}
-
delete el;
-
return true;
-
}
-
};
A demo file can be found here.

Add New Comment
Viewing 1 Comment
Thanks. Your comment is awaiting approval by a moderator.
Do you already have an account? Log in and claim this comment.
Do you already have an account? Log in and claim this comment.
Add New Comment
Trackbacks