Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

JavaScript에서 DOM 노드의 모든 자식 요소를 제거하려면 어떻게 해야 합니까?

<시간/>

의 자식 요소를 제거하려면

사용할 수 있습니다.

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

모든 하위 항목이 제거됩니다.

id는 'mList'입니다.

코드에서 -

로 작성할 수 있습니다.
<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>