mylesagray
mylesagray

Reputation: 8869

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

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?

Upvotes: 28

Views: 71356

Answers (6)

Hammerhead
Hammerhead

Reputation: 1367

2022 Answer:

Use element.replaceChildren()

Emptying a node replaceChildren() provides a very convenient mechanism for emptying a node of all its children. You call it on the parent node without any argument specified:

Doc

Upvotes: 2

Agamemnus
Agamemnus

Reputation: 1426

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/

Upvotes: 0

Antonio Bardazzi
Antonio Bardazzi

Reputation: 3236

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

$('my_container').update()

Upvotes: 4

Tom
Tom

Reputation: 7091

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.

Upvotes: 0

Rob Stevenson-Leggett
Rob Stevenson-Leggett

Reputation: 35679

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

Upvotes: 2

Alnitak
Alnitak

Reputation: 339816

If you have jQuery then:

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

Otherwise:

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

Upvotes: 53

Related Questions