The method removeChild does just that -- it removes a child element. This means you will have to call it on the parent of the element you wish to remove, so you have to change
Code:
d.removeChild(olddiv);
to
Code:
d.parentNode.removeChild(olddiv);
or, better yet, remove the "olddiv" part altogether, as it's the same thing as "d" in your code:
Code:
d.parentNode.removeChild(d);
Also, instead of using that counter to keep tracks of the created elements via their ids, you could just abandon the id part, which is a bit awkward, altogether, and instead keep track of the created elements by putting them in an array. Your code could look something like this:
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Add/Remove child: Javascript</title>
<script type="text/javascript">
var createdElements = [];
function addElement(parentNodeId) {
var parentNode = document.getElementById(parentNodeId);
var newdiv = document.createElement('div');
createdElements.push(newdiv);
newdiv.innerHTML = "Element Number " + createdElements.length + " has been added! <a href=\"#\" onclick=\"removeElement(this.parentNode)\">Remove the Element Number " + createdElements.length + "</a>";
parentNode.appendChild(newdiv);
}
function removeElement(element) {
element.parentNode.removeChild(element);
createdElements.splice(createdElements.indexOf(element), 1);
}
</script>
</head>
<body>
<p><a href="#" onclick="addElement('myDiv');">Add Some Elements</a></p>
<p><a href="#" onclick="addElement('myDiv1');">Add Some Elements</a></p>
<div id="myDiv"></div>
<div id="myDiv1"></div>
</body>
</html>