[ACCEPTED]-Removing an element from DOM-dom
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 24 thing to remember is that this solution 23 has quirks in some of the browsers (such as handling of newlines = "\n"). In 22 Prototype.js, we explicitly check for some of these quirks and tweak the logic appropriately.
And 21 of course it goes without saying that you 20 should use feature detection, not browser sniffing ;)
You also 19 don't really need to create new element 18 every time function is called. Simply store 17 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 16 this approach and keep element permanently, you 15 might also consider cleaning it (i.e. null
ing) on page unload, to 14 prevent possible leaks.
Unfortunately, merely 13 registering unload event handler prevents fast navigation (aka page 12 cache) in many browsers. Most of the JS 11 libraries already observe that event for 10 cleanup purposes, so if you're using one 9 (e.g. Prototype.js, jQuery, YUI), you shouldn't 8 worry about it - page cache will be disabled 7 anyway.
Otherwise, you might want to reconsider 6 your options and either always create element 5 at runtime, or employ different solution 4 altogether (e.g. String.prototype.replace
-based one):
function escapeHTML(str) {
return str.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
Oh, and finally, you 3 don't need to place ";" after 2 function declarations; it is function expressions that are recommended 1 to be ended with semicolons :)
DOM:
var node = document.getElementById('node_to_delete');
node.parentNode.removeChild(node);
jQuery:
$('#node_to_delete').remove();
0
IIRC you shouldn't have to care, since JS 3 is garbage collected. If it's a huge deal, you 2 could try parsing in chunks called via setTimeout()
with 1 a very short interval.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.