Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Xóa node con (child node) trong HTML bằng JavaScript


Dùng parent.removeChild(child) hoặc child.remove() (hiện đại, ngắn gọn). childNodes bao gồm cả text node (khoảng trắng, xuống dòng), nên cẩn thận khi dùng index.

Ví dụ

Xóa phần tử <li> đầu tiên trong danh sách:

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Xóa child node</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result { font-size: 20px; font-weight: 500; }
  </style>
</head>
<body>
  <h1>Xóa node con trong HTML bằng JavaScript</h1>
  <div class="result">
    <ul class="animal">
      <li>Bò</li>
      <li>Sư tử</li>
      <li>Hổ</li>
      <li>Trâu</li>
    </ul>
  </div>
  <button class="Btn">XÓA PHẦN TỬ ĐẦU</button>
  <h3>Nhấn nút để xóa <li> đầu tiên ("Bò")</h3>
  <script>
    const resEle = document.querySelector(".result");
    const animalList = document.querySelector(".animal");
    document.querySelector(".Btn").addEventListener("click", () => {
      // Cách hiện đại: dùng remove() trên chính element
      const firstLi = animalList.querySelector('li');
      if (firstLi) firstLi.remove();
      // Cách cũ: animalList.removeChild(animalList.children[0]);
    });
  </script>
</body>
</html>

Kết quả

Danh sách ban đầu: Bò, Sư tử, Hổ, Trâu. Sau khi nhấn: Sư tử, Hổ, Trâu.

Lưu ý: children chỉ lấy Element node (bỏ qua text node), an toàn hơn childNodes.