问题
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?
回答1:
If you have jQuery then:
$('#elName').empty();
Otherwise:
var node = document.getElementById('elName');
while (node.hasChildNodes()) {
node.removeChild(node.firstChild);
}
回答2:
The Prototype way is Element.update()
e.g.:
$('my_container').update()
回答3:
If you're using jQuery have a look at the .empty()
method http://api.jquery.com/empty/
回答4:
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/
回答5:
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.
来源:https://stackoverflow.com/questions/5057759/how-do-i-clear-the-contents-of-a-div-without-innerhtml