Javascript DOM How to - Remove a child








Question

We would like to know how to remove a child.

Answer


<!DOCTYPE html>
<html>
<body>
  <div id="div1">
    <div id="div2">
      <div id="data">data</div>
    </div><!--from ww w. ja  v  a  2  s  . c om-->
    <div id="div3">a-</div>
  </div>
    <script type='text/javascript'>
    
        var data = document.getElementById("data");
        var elem = document.getElementById("div2");
        while (elem.firstChild) {
            elem.removeChild(elem.firstChild);
        }
        document.getElementById("div3").appendChild(data);
    
    </script>
</body>
</html>

The code above is rendered as follows: