ใช้ parentNode.removeChild(childNode) เพื่อลบโหนดลูก (child node) ออกจาก DOM เมธอดนี้คืนค่าโหนดที่ถูกลบ (สามารถนำไปใช้ต่อได้) และโหนดจะถูกนำออกจากต้นไม้ DOM ทันที
ตัวอย่างโค้ด
<!DOCTYPE html>
<html lang="th">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ลบ 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>ลบ Child Node ใน HTML ด้วย JavaScript</h1>
<div style="color: green;" class="result">
<ul class="animal">
<li>วัว</li>
<li>สิงโต</li>
<li>เสือ</li>
<li>ควาย</li>
</ul>
</div>
<button class="Btn">คลิกที่นี่</button>
<h3>กดปุ่มเพื่อลบรายการแรก (วัว) ออกจากรายการ</h3>
<script>
const resEle = document.querySelector(".result");
const animalList = document.querySelector(".animal");
document.querySelector(".Btn").addEventListener("click", () => {
// childNodes[0] มักเป็น text node (whitespace) ใช้ children[0] สำหรับ element
const firstChild = animalList.children[0]; // วัว
if (firstChild) {
const removed = animalList.removeChild(firstChild);
console.log("ลบแล้ว:", removed.textContent);
}
});
</script>
</body>
</html>
ผลลัพธ์

เมื่อกดปุ่ม "คลิกที่นี่":

เมธอดลบ Node อื่นๆ
| เมธอด | คำอธิบาย | คืนค่า |
|---|---|---|
parent.removeChild(child) | ลบ child ที่ระบุ ต้องรู้ parent | โหนดที่ลบ |
child.remove() | ลบตัวเอง (DOM Level 4) — แนะนำ | undefined |
parent.replaceChild(new, old) | แทนที่ old ด้วย new | โหนดเก่า |
element.innerHTML = "" | ลบลูกทั้งหมด (เร็วแต่ไม่คืนค่าโหนด) | - |
ตัวอย่าง: ใช้ child.remove() (ทันสมัย ใช้ง่ายกว่า)
// ลบรายการแรก
const firstLi = document.querySelector(".animal li");
if (firstLi) firstLi.remove();
// ลบทุกรายการ
document.querySelectorAll(".animal li").forEach(li => li.remove());
// ลบตามเงื่อนไข
document.querySelectorAll(".animal li").forEach(li => {
if (li.textContent.includes("สิงโต")) li.remove();
});
childNodes vs children
childNodes: รวมทุกประเภท (Element, Text, Comment) —childNodes[0]มักเป็น whitespace text nodechildren: เฉพาะ Element nodes (HTML Elements) — แนะนำใช้ตัวนี้
Event Delegation (ลบรายการในลิสต์ใหญ่)
// ผูก event แค่ที่ parent
document.querySelector(".animal").addEventListener("click", (e) => {
if (e.target.tagName === "LI") {
e.target.remove(); // ลบรายการที่คลิก
}
});