HTML 문서에서 replaceChild() 메서드는 기존의 자식 노드를 새로운 노드로 교체하는 데 사용됩니다. 이 메서드는 부모 노드에서 호출되며, 첫 번째 인수로 새 노드를, 두 번째 인수로 교체할 기존 노드를 전달받습니다.
문법(Syntax)
replaceChild() 메서드의 기본 문법은 다음과 같습니다.
node.replaceChild(newNode, oldNode);
- newNode: 기존 노드를 대신하여 삽입할 새로운 노드입니다.
- oldNode: 교체 대상이 되는 기존 자식 노드입니다.
예제(Example)
다음 예제를 통해 replaceChild() 메서드의 실제 동작 방식을 살펴보겠습니다. 버튼을 클릭하면 과목 목록의 첫 번째 항목인 'Physics'가 'Biology'로 교체됩니다.
<!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() 메서드 데모</h1>
<p>안녕하세요, 제가 좋아하는 과목은:</p>
<ul id="subjectList">
<li>Physics</li>
<li id="chemistry">Chemistry</li>
<li>Maths</li>
<li>English</li>
</ul>
<button onclick="changeSubject()" class='btn'>Physics를 Biology로 변경</button>
<script>
function changeSubject() {
var textnode = document.createTextNode("Biology");
var list = document.getElementById("subjectList");
list.replaceChild(textnode, list.childNodes[0]);
}
</script>
</body>
</html>코드 설명
document.createTextNode("Biology")를 사용하여 'Biology'라는 텍스트를 가진 새로운 텍스트 노드를 생성합니다.document.getElementById("subjectList")로 과목 목록 요소에 접근합니다.list.replaceChild(textnode, list.childNodes[0])를 호출하여 목록의 첫 번째 자식 노드를 새로 생성한 노드로 교체합니다.
실행 결과(Output)
위 코드를 실행하면 다음과 같은 화면이 출력됩니다.

화면의 파란색 버튼을 클릭하면 과목 목록의 첫 번째 자식 노드가 아래와 같이 교체됩니다.

정리
replaceChild() 메서드는 DOM 조작 시 특정 노드를 삭제하고 새 노드를 추가하는 두 단계를 한 번에 처리할 수 있는 유용한 기능입니다. 단, 이 메서드는 반드시 부모 노드에서 호출해야 하며, 교체할 노드가 해당 부모의 직계 자식이어야 한다는 점을 기억해야 합니다.