Skip to content

Document.replaceChild fails #455

Description

@edemaine

Describe the bug
Since the 0.8.4 update, it's no longer possible to replace the (only) child of a document via replaceChild.

To Reproduce
https://stackblitz.com/edit/js-xmldom-template-3uxg9i?file=index.js

const xmldom = require('@xmldom/xmldom');
const doc = new xmldom.DOMParser().parseFromString('<svg/>', 'image/svg+xml');
doc.replaceChild(doc.createElement('svg'), doc.firstChild);

Expected behavior
I expect the (only) child of the document to change, as this still respects the one-child rule for documents. Instead I get:

Uncaught Error: Not found: child not in parent
    at _insertBefore (C:\Users\edemaine\Projects\svgtiler\node_modules\@xmldom\xmldom\lib\dom.js:772:9)
    at Document.insertBefore (C:\Users\edemaine\Projects\svgtiler\node_modules\@xmldom\xmldom\lib\dom.js:908:3)
    at Document.replaceChild (C:\Users\edemaine\Projects\svgtiler\node_modules\@xmldom\xmldom\lib\dom.js:478:8) {
  code: 8
}

Runtime & Version:
xmldom version: 0.8.4 (doesn't occur on 0.8.3)
runtime version: Node v18.7.0
other related software and version: Windows 11

Additional context
A workaround is to remove the old child and then append the old child:

doc.removeChild(doc.firstChild);
doc.appendChild(doc.createElement('svg'));

I also tested the following code in Chrome's DOMParser, and it works fine.

const doc = new DOMParser().parseFromString('<svg/>', 'image/svg+xml');
doc.replaceChild(doc.createElement('svg'), doc.firstChild);

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingneeds investigationInformation is missing and needs to be researched

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions