dom icon indicating copy to clipboard operation
dom copied to clipboard

replaceChildren can not replace a Document's documentElement

Open bwrrp opened this issue 3 years ago • 1 comments

Given a document that contains an element, and the following code:

const fragment = document.createDocumentFragment();
const element = fragment.appendChild(document.createElement('element'));
document.replaceChildren(fragment);

Expected result: document now only contains element Actual result: HierarchyRequestError

This is caused by replaceChildren calling "ensure pre-insertion validity without taking into consideration that the existing children of the document will be removed. This then fails on the following rule:

Otherwise, if node (the fragment) has one element child and either parent (the document) has an element child, child is a doctype, or child is non-null and a doctype is following child.

Perhaps an argument should be added to make this algorithm ignore pre-existing children when called from replaceChild, or perhaps replaceChildren should use a modified copy of these steps, as was done in replaceChild?

bwrrp avatar Jan 14 '22 14:01 bwrrp

Thanks for noticing this! I agree it makes sense to fix this. I think ideally we figure out a way to unify these two algorithms and make it suitable for all situations.

annevk avatar Jan 14 '22 16:01 annevk