
DOMParentNode의 replaceChildren 메서드는 노드의 모든 자식 노드를 제거하고, 새로운 노드들을 추가하는 메서드입니다. 이 메서드는 노드의 자식 노드의 순서를 유지하지 않습니다.
replaceChildren 메서드는 노드의 자식 노드가 변경되었을 때 노드의 상태를 업데이트합니다.
다음은 replaceChildren 메서드의 사용 예시입니다.
#hostingforum.kr
javascript
const parentNode = document.getElementById('parent');
const newChild = document.createElement('div');
newChild.textContent = '새로운 자식 노드';
parentNode.replaceChildren(newChild);
console.log(parentNode.firstChild); // 새로운 자식 노드
위의 코드에서, replaceChildren 메서드는 노드의 모든 자식 노드를 제거하고, 새로운 노드(newChild)를 추가합니다.
이 메서드는 노드의 자식 노드의 순서를 유지하지 않습니다. 따라서, parentNode.firstChild는 새로운 자식 노드를 참조합니다.
또한, 노드의 자식 노드가 변경되었을 때 노드의 상태를 업데이트합니다. 따라서, parentNode.replaceChildren 메서드를 호출하면 노드의 자식 노드가 변경되었을 때 노드의 상태가 업데이트됩니다.
replaceChildren 메서드는 노드의 자식 노드를 교체하는 데 사용할 수 있습니다. 예를 들어, 다음 코드를 보겠습니다.
#hostingforum.kr
javascript
const parentNode = document.getElementById('parent');
const oldChild = parentNode.firstChild;
parentNode.replaceChildren(document.createElement('div'));
console.log(oldChild); // undefined
위의 코드에서, replaceChildren 메서드는 노드의 모든 자식 노드를 제거하고, 새로운 노드를 추가합니다. 따라서, oldChild 변수는 undefined가 출력됩니다.
replaceChildren 메서드는 노드의 자식 노드를 교체하는 데 사용할 수 있습니다. 그러나, 노드의 자식 노드의 순서를 유지하지 않습니다.
따라서, replaceChildren 메서드를 사용할 때는 노드의 자식 노드의 순서를 유지해야 하는 경우에는 다른 메서드를 사용하는 것이 좋습니다.
2025-07-06 16:43