28

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?

Myles Gray
  • 8,711
  • 7
  • 48
  • 70
  • Where did you hear this? Do you have a link? – Oded Feb 20 '11 at 14:57
  • Isn't DOM manipulation via strings a bad idea? – Myles Gray Feb 20 '11 at 15:01
  • Jquery has `el.empty()`, but otherwise `el.innerHTML='';` is perfectly acceptable. Why do you think it's "not a good idea"? – tenfour Feb 20 '11 at 15:06
  • I assumed that `el.innerHTML = '';` was like manipulating the DOM with strings? – Myles Gray Feb 20 '11 at 15:08
  • 1
    @Myles: making the browser parse a string again might be slower than handing it a DOM tree (which is why people will recommend not just pasting strings around), but this doesn't apply here, for obvious reasons. – Ulrich Schwarz Feb 20 '11 at 15:10
  • 4
    Even though `''` is a string, it's an extremely lightweight way of "manipulating the DOM with strings". It's efficient, well-defined, and intuitive for coders. I would venture to say this is much faster than removing children in a loop. – tenfour Feb 20 '11 at 15:11
  • 2
    Actually this can be a problem, as IE relates to the innerHTML as a read only property on some elements, and might throw a nasty **"Unknown runtime error"**. So you better use this carefully. See also [This answer](http://stackoverflow.com/a/4729743/174944) – Mohoch Apr 04 '13 at 08:11

6 Answers6

53

If you have jQuery then:

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

Otherwise:

var node = document.getElementById('elName');
while (node.hasChildNodes()) {
    node.removeChild(node.firstChild);
}
Alnitak
  • 334,560
  • 70
  • 407
  • 495
4

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

$('my_container').update()
Antonio Bardazzi
  • 2,996
  • 1
  • 23
  • 20
2

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

Rob Stevenson-Leggett
  • 35,279
  • 21
  • 87
  • 141
0

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/

Agamemnus
  • 1,395
  • 4
  • 17
  • 41
0

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.

Tom
  • 6,947
  • 7
  • 46
  • 76
0

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

Hammerhead
  • 1,044
  • 8
  • 19
  • While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply. – jasie Oct 11 '22 at 08:23