I'm looking for a way where I can dynamically insert a button into a div from within another div, and when the button is clicked, the entire contents of the inner DIV disappear and all I'm left with is just the outer div and nothing else inside.
This is what I have so far:
<div ID="Parent">
<div ID="Child">
</div>
</div>
clickableobject=document.createElement('Button');
achild=document.getElementById("Child");
achild.appendChild(clickableobject);
clickableobject.onclick=new Function('document.getElementById("Parent").removeChild('+achild+')');
But when I run it, the onclick handler does fire, but it complains about the removeChild parameter and shows in the console error log that a number is being passed in as a parameter and the number is not -1. What can I do to specifically tell javascript to treat 'achild' as an object in all contexts?
I'm looking for a solution that works with older web browsers as well. All the better if there is a solution for IE7.
To remove the element, use elementNodeReference.remove();
which method removes the object from the tree it belongs to.
Try this:
var clickableobject = document.createElement('Button');
clickableobject.innerText = 'Click me';
var achild = document.getElementById("Child");
achild.appendChild(clickableobject);
clickableobject.onclick = function() {
achild.remove();
}
<div ID="Parent">
<div ID="Child">
</div>
</div>
Using Function constructor
without using remove()
, try this:
var clickableobject = document.createElement('Button');
clickableobject.innerText = 'Click me';
var achild = document.getElementById("Child");
achild.appendChild(clickableobject);
clickableobject.onclick = new Function('achild.parentNode.removeChild(achild);')
<div ID="Parent">
<div ID="Child">
</div>
</div>