Phương thức removeChild() trong HTML DOM trả về và loại bỏ nút con được chỉ định của nút cha trong tài liệu HTML.
Cú pháp
node.removeChild(node);
Ví dụ
Ví dụ sử dụng phương thức removeChild() để loại bỏ mục khỏi danh sách:
<!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>Môn học của sinh viên</h1>
<p>Chào, các môn học yêu thích của tôi:</p>
<ul id="subjectList">
<li>Vật lý</li>
<li>Hóa học</li>
<li>Toán học</li>
<li>Tiếng Anh</li>
</ul>
<button onclick="removeSubject()" class="btn">Loại bỏ môn học</button>
<script>
function removeSubject() {
var subList = document.getElementById("subjectList");
if (subList.hasChildNodes()) {
subList.removeChild(subList.childNodes[0]);
}
}
</script>
</body>
</html>
Kết quả
Nhấn nút Loại bỏ môn học để loại bỏ môn học khỏi danh sách.