如何删除父节点及其所有子节点 [英] How to remove a parent node with all its children
问题描述
我正在学习javascript的基础知识。现在它DOM和我被困在这里,我怎么能删除所有chldren的父节点。比如说我有像这样的HTML代码。
I am learning the basics of javascript. now it DOM and i am stuck here, How can i remove a parent node with all its chldren. eg say i have the html code like this.
<ul id ="parent">
<li>Hi</li>
<li>How</li>
<li>Are</li>
<li>You</li>
</ul>
我想删除< ul>
元素及其所有子< li>
节点。我尝试过这样做 document.getElementById('parent')。removeNode(true);
但它无效。有人能帮我一下吗。 ?
i wand to delete the <ul>
element with all its child <li>
nodes. I tried it to do like this document.getElementById('parent').removeNode(true);
but its not working. Can anyone help me here. ?
推荐答案
你需要获得 ul
元素的句柄然后要求其父元素通过传递 ul
处理父元素的 removeChild
方法来删除它。
You need to get a handle to the ul
element then ask its parent element to delete it by passing the ul
handle the parent's removeChild
method.
如果没有jQuery框架,你可以这样做:
This is how you would do it without the jQuery framework:
var x = document.getElementById('parent');
x.parentNode.removeChild(x);
当然如果你使用jQuery,它会很简单:
Of course if you used jQuery it would be simple like this:
$("#parent").remove();
这篇关于如何删除父节点及其所有子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!