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