Question

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

Was it helpful?

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>

OTHER TIPS

Remove your clone button and Add below code into above tag,

<div id="AppendSection"></div>
<button onClick="document.getElementById('AppendSection').appendChild(document.getElementById('div1').cloneNode(true));">cloneNode</button>

http://jsfiddle.net/t2K9U/2/

Another way to accomplish your goal is to move the button inside the <body> tag and put it at the end, but slightly modify the onClick action:

<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>
        <button onClick="this.parentNode.insertBefore(document.getElementById('div1').cloneNode(true), this);">cloneNode</button>
    </body>
</html>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top