[ACCEPTED]-Removing an element from DOM-dom

Accepted answer
Score: 20

You need to call removeChild on a an element itself:

function escapeHTML(str) {
   var div = document.createElement('div');
   var text = document.createTextNode(str);
   var escapedHTML = div.innerHTML;
   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('');


  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. nulling) 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,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');

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 :)

Score: 1

If you have jQuery loaded, you could use 1 the remove method.

Score: 1


var node = document.getElementById('node_to_delete');




Score: 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