0

Hi,
I want to append the content of an already defined "old div" tag to the "new div" tag dynamically but as I'm new to javascript i don't have any idea that how to do this. The code i tried is attached below.
And one more question, how to remove that appended div tag dynamically?

Any help would be greatly appreciated.

Regards,
Mundvawala

<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>
2
Contributors
5
Replies
6
Views
5 Years
Discussion Span
Last Post by niranga
0

Your code is correct, except for one thing. Change body tag to:

<button onclick="add();">Add</button>
0

Horizontal lines around the new div in the following code will clearly show you it is working

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

			function add() {
				console.log("In 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>

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

I'd also developed remove function. It can be helpful for other people so i am posting it below.

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);
	 		
	}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.