Computer >> Computer tutorials >  >> Programming >> Javascript

How can I remove all child elements of a DOM node in JavaScript?


To remove the child elements of <div>

we can use,

var list = document.getElementById("mList");
   while (list.hasChildNodes()) {
      list.removeChild(list.firstChild);
   }
}

It will remove the all child of

which id is 'mList'.

Example

In your code it can be written as -

<html>
   <body>
      <div id="mList" style="width:400px;background-color:gray">
         <ul>
            <li>li- child</li>
            <li>li- child</li>
         </ul>
      </div>
      <button onclick="mFunction()">Submit</button>
      <script>
         function mFunction() {
            var list = document.getElementById("mList");
            while (list.hasChildNodes()) {
               list.removeChild(list.firstChild);
            }
         }
      </script>
   </body>
</html>