
DOMElement::replaceWith 메서드는 지정된 요소의 자식 노드를 교체하는 데 사용됩니다. 이 메서드는 교체된 자식 노드를 삭제하고, 새로운 노드를 삽입합니다.
교체된 자식 노드는 DOM에서 제거되며, 부모 노드의 자식 노드 목록이 자동으로 업데이트됩니다. 따라서, DOMElement::replaceWith 메서드를 사용하여 자식 노드를 교체하면, 부모 노드의 자식 노드 목록이 최신 상태로 유지됩니다.
예를 들어, 다음 코드를 살펴보겠습니다.
#hostingforum.kr
php
$parent = new DOMElement('div');
$child1 = new DOMElement('p');
$child2 = new DOMElement('span');
$parent->appendChild($child1);
$parent->appendChild($child2);
echo $parent->childNodes->length; // 2
$parent->replaceChild(new DOMElement('h1'), $child1);
echo $parent->childNodes->length; // 1
위 코드에서, $parent 노드의 자식 노드 목록은 2개인 것을 확인할 수 있습니다. 그런 다음, $child1 노드를 교체한 후, $parent 노드의 자식 노드 목록은 1개로 업데이트된 것을 확인할 수 있습니다.
2025-04-24 05:56