เมธอด removeChild() ของ DOM จะคืนค่าและลบโหนดลูก (child node) ที่ระบุของโหนดที่กำหนดในเอกสาร HTML
รูปแบบการใช้งาน (Syntax)
node.removeChild(node);
ตัวอย่างการใช้งาน
ตัวอย่างด้านล่างแสดงการใช้งานเมธอด removeChild()
<!DOCTYPE html> <html> <head> <style> html{ height:100%; } body{ text-align:center; color:#fff; background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) center/cover no-repeat; height:100%; } p{ font-weight:700; font-size:1.2rem; } ul{ list-style-type: none; padding:0; } .btn{ background:#0197F6; border:none; height:2rem; border-radius:2px; width:50%; margin:2rem auto; display:block; color:#fff; outline:none; cursor:pointer; } .show{ font-size:1.5rem; font-weight:bold; } </style> </head> <body> <h1>วิชาที่นักเรียนชอบ</h1> <p>สวัสดี วิชาที่ผมชอบคือ:</p> <ul id="subjectList"> <li>ฟิสิกส์</li> <li>เคมี</li> <li>คณิตศาสตร์</li> <li>ภาษาอังกฤษ</li> </ul> <button onclick="removeSubject()" class="btn">ลบวิชา</button> <script> function removeSubject() { var subList = document.getElementById("subjectList"); if (subList.hasChildNodes()) { subList.removeChild(subList.childNodes[0]); } } </script> </body> </html>
ผลลัพธ์
โค้ดด้านบนจะให้ผลลัพธ์ดังนี้

คลิกที่ปุ่ม "ลบวิชา" เพื่อลบวิชาออกจากรายการ
