replaceChild method

  1. @mustCallSuper
Node? replaceChild(
  1. Node newNode,
  2. Node oldNode
)

Implementation

@mustCallSuper
Node? replaceChild(Node newNode, Node oldNode) {
  Node? replacedNode;
  if (childNodes.contains(oldNode)) {
    newNode._ensureOrphan();
    bool isOldNodeConnected = oldNode.isConnected;
    int referenceIndex = childNodes.indexOf(oldNode);
    oldNode.parentNode = null;
    newNode.parentNode = this;
    replacedNode = oldNode;
    childNodes[referenceIndex] = newNode;

    // To insert a node into a parent before a child, run step 9 from the spec:
    // 9. Run the children changed steps for parent when inserting a node into a parent.
    // https://dom.spec.whatwg.org/#concept-node-insert
    childrenChanged();

    if (isOldNodeConnected) {
      oldNode.disconnectedCallback();
      newNode.connectedCallback();
    }
  }
  return replacedNode;
}