
DomParentNode::replaceChildren 메서드는 DOM 트리에서 특정 노드의 자식을 모두 제거하고 새로운 자식을 삽입하는 메서드입니다.
이 메서드는 노드의 자식 노드를 모두 제거하고 새로운 노드를 삽입하는 것과는 다릅니다. replaceChildren 메서드는 자식 노드 자체를 제거하지 않고, 자식 노드의 내용을 모두 제거하고 새로운 내용을 삽입합니다.
replaceChildren 메서드는 노드의 자식 노드가 여러 개인 경우에도 동작합니다.
예를 들어, 다음 코드는 특정 노드의 자식을 모두 제거하고 새로운 자식을 삽입하는 방법을 보여줍니다.
#hostingforum.kr
javascript
const parentNode = document.getElementById('parent');
const newNode = document.createElement('div');
newNode.textContent = '새로운 노드';
parentNode.replaceChildren(newNode);
이 코드는 parentNode 노드의 자식을 모두 제거하고 newNode 노드를 삽입합니다.
또한, 다음 코드는 노드의 자식 노드를 모두 제거하고 새로운 노드를 삽입하는 방법을 보여줍니다.
#hostingforum.kr
javascript
const parentNode = document.getElementById('parent');
const newNode = document.createElement('div');
newNode.textContent = '새로운 노드';
while (parentNode.firstChild) {
parentNode.removeChild(parentNode.firstChild);
}
parentNode.appendChild(newNode);
이 코드는 parentNode 노드의 자식을 모두 제거하고 newNode 노드를 삽입합니다.
replaceChildren 메서드는 DOM 트리에서 자식 노드의 내용을 모두 제거하고 새로운 내용을 삽입하는 메서드입니다. 이 메서드는 노드의 자식 노드가 여러 개인 경우에도 동작합니다.
2025-07-01 05:12