Search code examples
javascripthtmlappendchilddocument-bodyclonenode

Elements outside <BODY> is taken inside <BODY>


I have the following code:

<html>
    <head>
        <script>
        </script>

        <style>
        </style>
    </head>
    <body>
        <div id=div1 style="border:5px solid green" onClick="alert(this.id)">hi
            <div id=div2 style="border:2px solid yellow">hello</div>
            <div id=div3 style="border:2px solid red">world</div>
        </div>
    </body>
    <button onClick="document.body.appendChild(document.getElementById('div1').cloneNode(true));">cloneNode</button>
</html>

I wanted to make the clone of the div1 to appear above the cloneNodebutton and hence kept the button outside the <body>. But each time I click on the cloneNodebutton the new element appears below the cloneNodebutton although I appended the new node to the <body>element(using appendChild()) and the button is outside the <body> element. So, are all the elements even those outside the <body>(as specified in the script) included or considered inside the <body> at runtime. Please help me understand this.

Check the demo


Solution

  • actual browser may rewrite invalid html (and, writing elements outside is not really natural) . You can add an other surrounding div#id and use it to append correctly.

    Try this (I also added quotes for element' ids):

    <html>
        <head>
            <script>
            </script>
    
            <style>
            </style>
        </head>
        <body>
             <div id="main">
            <div id="div1" style="border:5px solid green" onClick="alert(this.id)">hi
                <div id="div2" style="border:2px solid yellow">hello</div>
                <div id="div3" style="border:2px solid red">world</div>
            </div>
             </div>
          <button onClick="document.getElementById('main').appendChild(document.getElementById('div1').cloneNode(true));">cloneNode</button>
    
        </body>
    </html>