skip to Main Content

Can an Element created by document.createElement be added to another document?

   const element = document.createElement("div");
   anotherDocument.body.appendChild(element)

2

Answers


  1. Yes it can, and doing so will automatically call anotherDocument.adoptNode(element)1.

    1. Well it will call the same internal adopt algorithm, it won’t call that method exactly.

    const anotherDocument = document.implementation.createHTMLDocument();
    const element = document.createElement("div");
    console.log("before", element.ownerDocument === anotherDocument, element.ownerDocument === document ); // false, true
    anotherDocument.body.appendChild(element);
    console.log("after", element.ownerDocument === anotherDocument, element.ownerDocument === document ); // true, false
    Login or Signup to reply.
  2. Elements created by document.createElement cannot be added to other documents. Nodes in the DOM belong to specific documents, and nodes from one document cannot be inserted into another without first cloning or importing them.

    To add an element to another document, you need to create a copy using cloneNode or importNode first. You need to insert the copy into the target document using the appropriate DOM manipulation method.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search