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

会有一股神秘感。 提交于 2019-11-30 01:35:57

If you have jQuery then:

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

Otherwise:

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

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

$('my_container').update()

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

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/

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!