如何使用 jQuery 從父節點中移除所有子節點?


使用 jQuery empty() 方法可以從父節點中移除所有子節點。

示例

可以嘗試執行以下程式碼,使用 jQuery 從父節點中移除所有子節點

現場演示

<!DOCTYPE html>
<html>
<head>
<style>

</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
      $("#button1").click(function(){
         $("ul").empty();
      });

});
</script>
</head>

<body>
  <div>
    <ul>
      <li>li (child)</li>
      <li>li (child)</li>
      <li>li (child)</li>
      <li>li (child)</li>
    </ul>  
  </div>
  <button id="button1">Remove</button>
  <p>Click Remove to remove all child nodes.</p>
</body>
</html>

更新於: 2020 年 6 月 15 日

349 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告