简体   繁体   English

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

[英]How to remove a parent node with all its children

I am learning the basics of javascript. 我正在学习javascript的基础知识。 now it DOM and i am stuck here, How can i remove a parent node with all its chldren. 现在它DOM和我被困在这里,我怎么能删除所有chldren的父节点。 eg say i have the html code like this. 比如说我有像这样的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. 我想用它的所有子<li>节点删除<ul>元素。 I tried it to do like this document.getElementById('parent').removeNode(true); 我试着这样做就像这个document.getElementById('parent').removeNode(true); but its not working. 但它不起作用。 Can anyone help me here. 有人能帮我一下吗。 ?

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. 您需要获取ul元素的句柄,然后通过传递父removeChildremoveChild方法的ul句柄来要求其父元素删除它。

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();

try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM