เมธอด DOM replaceChild() แทนที่โหนดย่อยด้วยโหนดใหม่ในเอกสาร HTML
ไวยากรณ์
ต่อไปนี้เป็นไวยากรณ์ -
node.replaceChild(newNode,oldNode);
ตัวอย่าง
ให้เราดูตัวอย่างของวิธี replaceChild() -
<!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>DOM replaceChild() Method Demo</h1>
<p>Hi, My favourite subjects are:</p>
<ul id="subjectList">
<li>Physics</li>
<li id="chemistry">Chemistry</li>
<li>Maths</li>
<li>English</li>
</ul>
<button onclick="changeSubject()" class='btn'>Change Physics to Biology</button>
<script>
function changeSubject() {
var textnode = document.createTextNode("Biology");
var list = document.getElementById("subjectList");
list.replaceChild(textnode, list.childNodes[0]);
}
</script>
</body>
</html> ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

คลิกที่ “สีน้ำเงิน ” เพื่อแทนที่ลูกคนแรกของรายการเรื่อง -
