Search code examples
javascripthtmlchild-nodes

How can I delete all Child Nodes inside a div in one shot in such a way it is empty after that code lines are executed using javascript?


I'm trying to implement a piece of code in javascript which removes all child nodes inside a div in such a way it is empty after the execution of the code. I was thinking of using a while loop and the hasChildNodes() method applied to this div, and inside the argument of the loop insert a line of code which removes the first-child of this div in each check until it removes all child Nodes, but I find it quite cumbersome. Is there a faster way to get rid of all elements inside a div using some kind of method?


Solution

  • Jquery's $.html() method.

    like so:

    $('#parent').html('');
    

    all child elements inside will be replaced with '';

    or

    $('div').children().each(function(index){
        $(this).remove();
    });