Rajesh Paul Rajesh Paul - 5 months ago 12
Javascript Question

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
cloneNode
button and hence kept the button outside the
<body>
. But each time I click on the
cloneNode
button the new element appears below the
cloneNode
button 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

Answer

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>
Comments