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

JavascriptWeb DevelopmentFront End Technology

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>
raja
Published on 27-Sep-2018 14:20:44
Advertisements