Live Chat Icon For mobile
Live Chat Icon

How can I add and remove an Html element dynamically using javascript?

Platform: ASP.NET| Category: Client Side Scripting

Below is the javascript code which is used to add and remove div elements dynamically.Here the div tags are added in one base
div tag container.


<script>
	function AddHtmlElement()
	{
		var divElement = document.getElementById(’MYDIV’); 
		var divNumber= document.getElementById(’hiddenValue’); 
		var num = (document.getElementById(’hiddenValue’).value -1)+ 2; 
		divNumber.value = num; 
		var newdiv = document.createElement(’div’); 
		var divIdName = ’MYDIV’+num;
		newdiv.setAttribute(’id’,divIdName); 
		var divLoadedText=’Div ’+num+’ Is Added!’;	
		divElement.appendChild(newdiv);
		newdiv.innerHTML =divLoadedText+' '+'<a href=’#’ onclick=RemoveHtmlElement(’'+divIdName+'’)>Remove div ’'+divIdName+'’</a>';  
	}
	functionRemoveHtmlElement(divNum)
	{ 
		var divId = document.getElementById(’MYDIV’); 
		var childId = document.getElementById(divNum); 
		divId.removeChild(childId); 
	}
</script>

<form id='Form1' >
	<input id='hiddenValue' type='hidden' value='0'>
	<p>
		<a href='#' onclick='AddHtmlElement()'>Add Html Elements</a>
	</p>
	<div id='MYDIV'></div>
</form>

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.