First of all, the (x)html is real simple.
xHTML Snippet
Code: Select all
<input type="hidden" value="0" id="theValue" />
<p><a href="javascript:;" onclick="addElement();">Add Some Elements</a></p>
<div id="myDiv"> </div>
Now the JS functions
addElement JavaScript Function
Code: Select all
function addElement() {
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML = 'Element Number '+num+' has been added! <a href=\'#\' onclick=\'removeElement('+divIdName+')\'>Remove the div "'+divIdName+'"</a>';
ni.appendChild(newdiv);
}
Code: Select all
function removeElement(divNum) {
var d = document.getElementById('myDiv');
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}
The next three lines basically grab the value of the hidden input element and give your function a starting number to begin with. Then each time the function is called, your value is incremented. This is important for when you need to remove elements, since you’ll need unique id’s.
You’ll notice next the createElement is used to… well… make a new div element. But wait, it needs an id. Thus, we use the setAttribute method to append an id and a value to it. At this point, we have the uniquely named divIdName and we will plug that into the equation for our newdiv object.
Now you’re ready for some content to put inside your dynamic div element using the innerHTML property. And this is when it gets fun. Within your HTML supplied in the innerHTML of the dynamically created div element, you need to provide a link to remove itself. After all, that’s the point of this whole thing, right? It wouldn’t be flexible if all we could do is only add and not remove.
So, a link is put inside with an event handler that calls the function removeElement. Great. Simple enough. Let’s move onto that function.
Okay, now that is easy. First off, it grabs the same parent div element by using getElementById and stores it in a variable. We then get the element to which we passed in as an argument to the function (which was created from the addEvent function), and we store that in another variable.
Code: Select all
d.removeChild(olddiv);