-5

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

4

3 回答 3

2

实际的浏览器可能会重写无效的 html(而且,在外面写元素并不是很自然)。您可以添加其他周围的 div#id 并使用它来正确附加。

试试这个(我还为元素的 id 添加了引号):

<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>
于 2013-10-31T13:55:11.800 回答
2

删除您的克隆按钮并将以下代码添加到上面的标签中,

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

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

于 2013-10-31T13:57:26.023 回答
0

实现目标的另一种方法是将标签的按钮移动<body>并放在最后,但稍微修改一下onClick操作:

<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>
于 2016-06-13T07:36:43.563 回答