
DomParentNode::replaceChildren 메서드는 DOM 노드의 자식 노드를 모두 제거하고, 새로운 자식 노드를 추가하는 메서드입니다.
이 메서드는 현재 노드의 자식 노드들을 모두 제거하고, 새로운 자식 노드들을 추가합니다.
예를 들어, 다음 코드를 살펴보겠습니다.
#hostingforum.kr
javascript
const parent = document.getElementById('parent');
const child1 = document.createElement('div');
const child2 = document.createElement('span');
child1.textContent = '자식 1';
child2.textContent = '자식 2';
parent.appendChild(child1);
parent.appendChild(child2);
console.log(parent.children); // [div, span]
parent.replaceChildren(child2, child1);
console.log(parent.children); // [span, div]
위 코드에서, `replaceChildren` 메서드는 현재 노드의 자식 노드들을 모두 제거하고, `child2`와 `child1`를 추가합니다.
이러한 메서드는 노드의 순서를 관리하는 데 도움이 됩니다. 노드의 순서를 변경하고 싶을 때, 노드를 하나씩 제거하고 추가하는 대신, `replaceChildren` 메서드를 사용하여 한번에 노드의 순서를 변경할 수 있습니다.
2025-08-07 11:48