Phương thức replaceChild() trong HTML DOM thay thế một nút con bằng một nút mới trong tài liệu HTML.
Cú pháp
node.replaceChild(newNode, oldNode);
Ví dụ
Ví dụ sử dụng phương thức replaceChild() để thay đổi môn học trong danh sách:
<!DOCTYPE html>
<html>
<head>
<style>
html { height: 100%; }
body { text-align: center; color: #fff; background: #ff7f5094; 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: 35%; margin: 2rem auto; display: block; color: #fff; outline: none; cursor: pointer; }
.show { font-size: 1.5rem; }
</style>
</head>
<body>
<h1>Demo phương thức replaceChild() DOM</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 id="chemistry">Hóa học</li>
<li>Toán học</li>
<li>Tiếng Anh</li>
</ul>
<button onclick="changeSubject()" class='btn'>Thay đổi Vật lý thành Sinh học</button>
<script>
function changeSubject() {
var textnode = document.createTextNode("Sinh học");
var list = document.getElementById("subjectList");
list.replaceChild(textnode, list.childNodes[0]);
}
</script>
</body>
</html>
Kết quả
Nhấn nút Xanh dương để thay thế nút con đầu tiên của danh sách môn học.