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?
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 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.
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/
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
精彩评论