简体   繁体   中英

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'.

my div is some what like this.

<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 :

 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

firstChild returns the first nested element. On successful removal, the next child will be the first child,so as long as firstChild is there, it will execute

 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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