You need to call removeChild
on a an element itself:
function escapeHTML(str) {
var div = document.createElement('div');
var text = document.createTextNode(str);
div.appendChild(text);
var escapedHTML = div.innerHTML;
div.removeChild(text);
return escapedHTML;
}
One thing to remember is that this solution has quirks in some of the browsers (such as handling of newlines = "\n"). In Prototype.js, we explicitly check for some of these quirks and tweak the logic appropriately.
And of course it goes without saying that you should use feature detection, not browser sniffing ;)
You also don't really need to create new element every time function is called. Simply store it in a closure. For example:
var escapeHTML = (function(){
var div = document.createElement('div');
var text = document.createTextNode('');
div.appendChild(text);
return function(str) {
text.data = str;
return div.innerHTML;
};
})();
If you employ this approach and keep element permanently, you might also consider cleaning it (i.e. null
ing) on page unload, to prevent possible leaks.
Unfortunately, merely registering unload event handler prevents fast navigation (aka page cache) in many browsers. Most of the JS libraries already observe that event for cleanup purposes, so if you're using one (e.g. Prototype.js, jQuery, YUI), you shouldn't worry about it - page cache will be disabled anyway.
Otherwise, you might want to reconsider your options and either always create element at runtime, or employ different solution altogether (e.g. String.prototype.replace
-based one):
function escapeHTML(str) {
return str.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
Oh, and finally, you don't need to place ";" after function declarations; it is function expressions that are recommended to be ended with semicolons :)