最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript Appending another Div data on Div Tag Dynamically - Stack Overflow

programmeradmin3浏览0评论

I want to append the content of an already defined "old div" tag to the "new div" tag dynamically but its not working. The code i tried is attached below. And one more question, how to remove that appended div tag dynamically?

<html>
<head>
<script type="text/javascript">

function add() {

var i = document.getElementById( 'old' );
var d = document.getElementById( 'new' );
d.appendChild( i );
}
</script>

</head>
<body>
<div id="old">
Content of old div
</div>

<div id="new">
</div>
<button onclick="add()">Add</button>
</body>
</html>

I want to append the content of an already defined "old div" tag to the "new div" tag dynamically but its not working. The code i tried is attached below. And one more question, how to remove that appended div tag dynamically?

<html>
<head>
<script type="text/javascript">

function add() {

var i = document.getElementById( 'old' );
var d = document.getElementById( 'new' );
d.appendChild( i );
}
</script>

</head>
<body>
<div id="old">
Content of old div
</div>

<div id="new">
</div>
<button onclick="add()">Add</button>
</body>
</html>
Share Improve this question asked Nov 29, 2011 at 20:00 Naeem Ul WahhabNaeem Ul Wahhab 2,4954 gold badges35 silver badges61 bronze badges 1
  • 1 It sure is a great idea. – Naeem Ul Wahhab Commented Nov 29, 2011 at 20:11
Add a comment  | 

2 Answers 2

Reset to default 9

Try this

var i = document.getElementById( 'old' );
var d = document.getElementById( 'new' );
d.innerHTML += i.innerHTML;

ok I solved it. There was some error in my code. Its working now.

    <html>
    <head>
        <script type="text/javascript">

            function add() {

        var i = document.getElementById( 'old' );

        var d = document.createElement( 'div' );
        d.id = "new1";
        d.innerHTML = i.innerHTML ;
        var p = document.getElementById('new');

        p.appendChild(d);

    }

    function removeLocation() {

        var d = document.getElementById( 'new1' );

        var p = document.getElementById('new');

        p.removeChild(d);

    }
        </script>

    </head>
    <body>
        <div id="old">
            Content of old div
        </div>

        <hr/>
        <div id="new">
        </div>
        <hr/>
        <button onclick="add();">Add</button><br>
        <button onclick="removeLocation();">Remove</button>
    </body>
    </html>
发布评论

评论列表(0)

  1. 暂无评论