如何使用JavaScript删除HTML中的子节点?
时间:2020-03-05 18:40:11 来源:igfitidea点击:
是否有类似document.getElementById(" FirstDiv")。clear()
的功能?
解决方案
回答
我们应该能够使用节点的.RemoveNode方法或者父节点的.RemoveChild方法。
回答
如果要清除div并删除所有子节点,则可以输入:
var mydiv = document.getElementById('FirstDiv'); while(mydiv.firstChild) { mydiv.removeChild(mydiv.firstChild); }
回答
我们可能应该使用JavaScript库执行此类操作。
例如,MochiKit具有功能removeElement,而jQuery具有功能remove。
回答
我们必须先删除在节点上设置的所有事件处理程序,然后再删除它,以避免IE中的内存泄漏
回答
要回答原始问题,可以通过多种方法来完成,但是以下是最简单的方法。
如果我们已经有要删除的子节点的句柄,即我们有一个JavaScript变量,该变量包含对它的引用:
myChildNode.parentNode.removeChild(myChildNode);
显然,如果我们不使用已经在执行此操作的众多库之一,则需要创建一个函数来抽象出这一点:
function removeElement(node) { node.parentNode.removeChild(node); }
编辑:正如其他人提到的那样:如果我们有任何事件处理程序连接到要删除的节点,我们将要确保在最后一个对要删除的节点的引用超出范围之前先断开它们的连接,以免执行不佳JavaScript解释器泄漏内存。
回答
jQuery解决方案
的HTML
<select id="foo"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select>
Java脚本
// remove child "option" element with a "value" attribute equal to "2" $("#foo > option[value='2']").remove(); // remove all child "option" elements $("#foo > option").remove();
参考:
属性等于选择器[名称=值]
Selects elements that have the specified attribute with a value exactly equal to a certain value.
子选择器(父>子)
Selects all direct child elements specified by "child" of elements specified by "parent"
。消除()
Similar to .empty(), the .remove() method takes elements out of the DOM. We use .remove() when we want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.