简体   繁体   English

如何从div中删除子元素

[英]How to remove child element from div

I am getting error some this like this. 我得到这样的错误。

Uncaught TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'. 未捕获的TypeError:无法在“节点”上执行“ removeChild”:参数1的类型不是“节点”。

my div is some what like this. 我的div是这样的。

<div class="" style="" id ="P1">
    <div class= " " style="" id ="C1">
        <Input>Val</Input>
    </div>
    <div class= " child2" style="" id ="C2">
        <Input>Val2</Input>
    </div>
</div>

I want to remove all the child but getting the error. 我想删除所有孩子,但收到错误消息。

var myClass = val.("Data").el.dom // My Parent div
    myClass.removeChild();

Here is what I am trying. 这是我正在尝试的。 Can anybody help me how to get this. 有人可以帮我怎么做吗?

To remove all the child of div with id P1 you may simply do this : 要删除ID为P1的div所有子代,您可以执行以下操作:

 document.querySelector("#P1").innerHTML = ""; //or use this //document.getElementById("P1").innerHTML = ""; //or a jQuery solution like this // $('#P1').html(""); 
 <div class="" style="" id="P1"> <div class=" child1" style="" id="C1"> <Input>Val</Input> </div> <div class=" child2" style="" id="C2"> <Input>Val2</Input> </div> </div> 

removeChild method removes a specific child node.If need to remove all the child ,put it in a while loop removeChild方法删除一个特定的子节点。如果需要删除所有子节点,则将其放入while循环中

firstChild returns the first nested element. firstChild返回第一个嵌套元素。 On successful removal, the next child will be the first child,so as long as firstChild is there, it will execute 成功删除后,下一个孩子将是第一个孩子,因此只要firstChild在此,它将执行

 var prtElement = document.getElementById('P1'); while (prtElement.firstChild) { prtElement.removeChild(prtElement.firstChild); } 
 <div class="Parent" style="" id="P1"> <div class=" child1" style="" id="C1"> <Input>Val</Input> </div> <div class=" child2" style="" id="C2"> <Input>Val2</Input> </div> </div> 

I would recommend using jQuery: 我建议使用jQuery:

$(document).ready(function(){
/* or whatever else function you want */
$("#parent").children().remove();
});

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

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