Home » Html » How do I clear the contents of a div without innerHTML = “”;

How do I clear the contents of a div without innerHTML = “”;

Posted by: admin December 4, 2017 Leave a comment

Questions:

I have a div that is filled by JS created DOM elements,

I want the div to be cleared upon the JS function repeating, however I have heard that using document.getElementById('elName').innerHTML = ""; is not a good idea,

What is a valid alternative to doing this to clear the div’s contents?

Answers:

If you have jQuery then:

$('#elName').empty();

Otherwise:

var node = document.getElementById('elName');
while (node.hasChildNodes()) {
    node.removeChild(node.firstChild);
}

Questions:
Answers:

The Prototype way is Element.update() e.g.:

$('my_container').update()

Questions:
Answers:

If you’re using jQuery have a look at the .empty() method http://api.jquery.com/empty/

Questions:
Answers:

You can redefine .innerHTML. In Firefox and Chrome, it’s not a problem to clear the elements with .innerHTML = “”. In IE, it is, because any child elements are immediately cleared. In this example, “mydiv.innerHTML” would normally return “undefined”. (without the redefine, that is, and in IE 11 as of the date of this post creation)

if (/(msie|trident)/i.test(navigator.userAgent)) {
 var innerhtml_get = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "innerHTML").get
 var innerhtml_set = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "innerHTML").set
 Object.defineProperty(HTMLElement.prototype, "innerHTML", {
  get: function () {return innerhtml_get.call (this)},
  set: function(new_html) {
   var childNodes = this.childNodes
   for (var curlen = childNodes.length, i = curlen; i > 0; i--) {
    this.removeChild (childNodes[0])
   }
   innerhtml_set.call (this, new_html)
  }
 })
}

var mydiv = document.createElement ('div')
mydiv.innerHTML = "test"
document.body.appendChild (mydiv)

document.body.innerHTML = ""
console.log (mydiv.innerHTML)

http://jsfiddle.net/DLLbc/9/

Questions:
Answers:

You could loop through its children and remove then, ie.

var parDiv = document.getElementById('elName'),
    parChildren = parDiv.children, tmpChildren = [], i, e;

    for (i = 0, e = parChildren.length; i < e; i++) {
        tmpArr.push(parChildren[i]);
    }

    for (i = 0; i < e; i++) {
        parDiv.removeChild(tmpChildren[i]);
    }

Or use .empty() if you are using jQuery.
This is just an alternative solution, a while loop is much more elegant.