Removing an item from the DOM

I use this method to exclude lines of HTML code on the client side:

function escapeHTML(str)
{
   var div = document.createElement('div');
   var text = document.createTextNode(str);
   div.appendChild(text);
   return div.innerHTML;
}; 

I am a bit worried about memory leaks because I am creating a DOM element and not destroying it. This page is very Ajax'ed and will be updated very rarely, so there can be hundreds of method calls without reloading the page, which means that these objects will accumulate, slowing down DOM traffic (for example, using jQuery).

I tried using document.removeChild(div), but IE gives the error "htmlfile: Invalid argument."

Any ideas?

Thanks Andrew

+3
source share
4 answers

You need to call removeChildfor the 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;
}

, (, = "\n" ). Prototype.js .

, , , , ;)

, . . :

var escapeHTML = (function(){

  var div = document.createElement('div');
  var text = document.createTextNode('');

  div.appendChild(text);

  return function(str) {
    text.data = str;
    return div.innerHTML;
  };
})();

, (.. null ing) , .

, unload (aka page cache) . JS , , (, Prototype.js, jQuery, YUI), - .

, (, String.prototype.replace):

function escapeHTML(str) {
  return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}

, , , ";" ; , :)

+20

jQuery, .

+1

DOM:

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

JQuery

$('#node_to_delete').remove();
+1

IIRC you do not need to care, because JS collect garbage. If this is a huge deal, you can try parsing in chunks called through setTimeout()at a very short interval.

0
source

Source: https://habr.com/ru/post/1718579/


All Articles