954,561 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Error in appending DIV tag dynamically

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>
mundvawala
Newbie Poster
14 posts since Apr 2010
Reputation Points: 10
Solved Threads: 0
 

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

<button onclick="add();">Add</button>
niranga
Junior Poster
163 posts since Apr 2010
Reputation Points: 21
Solved Threads: 21
 

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>
niranga
Junior Poster
163 posts since Apr 2010
Reputation Points: 21
Solved Threads: 21
 

Thank you very much @ niranga.

mundvawala
Newbie Poster
14 posts since Apr 2010
Reputation Points: 10
Solved Threads: 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);
	 		
	}
mundvawala
Newbie Poster
14 posts since Apr 2010
Reputation Points: 10
Solved Threads: 0
 

Welcome :)

niranga
Junior Poster
163 posts since Apr 2010
Reputation Points: 21
Solved Threads: 21
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: