Search code examples
javascripthtmlappendchild

HTML - appendChild() in document itself (body)


From W3S, regarding what's a node: "The document itself is a document node" ( Source ). The appendChild() method is said to work like this: node1.appendChild(node2). If I am understanding nodes correct, shouldn't I be able to append something into the document body? I have tried document.appendChild(...) and window.appendChild(...), it didn't work. Right now I have to create a sort of frame and then append into that ( See example snippet ).

How can I append a node into the document as a whole? Instead of, as in the example below, append into a new div?

function append(){
  box = document.createElement("div");
  box.style.backgroundColor = "#F00";
  box.style.width = "50px"; 
  box.style.height = "50px"; 
  document.getElementById("frame").appendChild(box); 
}
<div id="frame" style="position:absolute; top:90px; width:100px; height:100px;border-style:solid; border-width:2px; border-color:#000;"></div>

<input type=button value="Append" onClick="append()">


Solution

  • Instead of appending it to the document, you will need to append it to the body.

    The issue with appending it to the document, is that only one element can be on the document at a time, and it is the body element currently.

    function append(){
      box = document.createElement("div");
      box.style.backgroundColor = "#F00";
      box.style.width = "50px"; 
      box.style.height = "50px"; 
      document.body.appendChild(box); 
    }
    <div id="frame" style="position:absolute; top:50px; width:100px; height:100px;border-style:solid; border-width:2px; border-color:#000;"></div>
    
    <input type=button value="Append" onClick="append()">