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>

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

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

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>

Thank you very much @ niranga.

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);
	 		
	}

Welcome :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.