无论出于何种原因,元素都无法在JavaScript中销毁自己。 jQuery为此提供了一种方法 ,这很不错,因为这是我们的想法:
$(".remove-me").remove();
但是JavaScript中没有直接的等效项。 相反,您需要选择父元素并使用removeChild
。
因此,如果您有:
<div class="module">
<p>Stuff.</p>
<div class="remove-me">...</div>
</div>
您需要执行以下操作:
var thingToRemove = document.querySelectorAll(".remove-me")[0];
thingToRemove.parentNode.removeChild(thingToRemove);
或者,如果您有对元素的引用,并且想清空其中的所有元素 ,但请保留该元素 :
mydiv = document.getElementById('empty-me');
while (mydiv.firstChild) {
mydiv.removeChild(mydiv.firstChild);
}
翻译自: https://css-tricks.com/snippets/javascript/remove-element/