Javascript 如何删除父节点及其所有子节点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8571512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:32:51  来源:igfitidea点击:

How to remove a parent node with all its children

javascript

提问by ScoRpion

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.

我正在学习 javascript 的基础知识。现在它是 DOM,我被困在这里,如何删除父节点及其所有子节点。例如说我有这样的 html 代码。

<ul id ="parent">
    <li>Hi</li>
    <li>How</li>
    <li>Are</li>
    <li>You</li>
</ul>

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>元素及其所有子<li>节点。我试过这样做,document.getElementById('parent').removeNode(true);但它不起作用。有人能帮我一下吗。?

回答by Roman

You need to get a handle to the ulelement then ask its parent element to delete it by passing the ulhandle the parent's removeChildmethod.

您需要获取ul元素的句柄,然后通过将ul句柄传递给父元素的方法来要求其父元素删除它removeChild

This is how you would do it without the jQuery framework:

如果没有 jQuery 框架,您将如何做到这一点:

var x = document.getElementById('parent');
x.parentNode.removeChild(x);

Of course if you used jQuery it would be simple like this:

当然,如果你使用 jQuery,它会像这样简单:

$("#parent").remove();

回答by hungneox

try this:

尝试这个:

var childNode = document.getElementById("parent");
childNode.parentNode.removeChild(childNode);