You already have a reference to the new paragraph in the writePara
function and you already used it once in the edit handler, so why don't you use it again in the delete handler?
button2.onclick =
(
function ()
{
newParagraph.parentNode.removeChild(newParagraph);
button.parentNode.removeChild(button);
button2.parentNode.removeChild(button2);
}
);
Here's how it works: http://jsbin.com/nohud/1/edit. Write something in the input and click outside of it a few times to generate some paragraphs.
Edit: The code above utilizes closures. It is important to understand that each time writePara
is called, the newParagraph
variable points to a new DOM element and each click event handler defined in the same function has access to that specific element in the newParagraph
variable. So whenever the edit/delete handlers are called newParagraph
is the element with which the associated buttons have been created when writePara
has been called.
Here's some code that explains that clearer that I do:
function init() {
var name = "Mozilla"; // name is a local variable created by init
function displayName() { // displayName() is the inner function, a closure
alert (name); // displayName() uses variable declared in the parent function
}
displayName();
}
init();
It is taken from here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures. More also here: How do JavaScript closures work?.
From there on newParagraph.parentNode
is the container containing the new paragraph, so newParagraph.parentNode.removeChild(newParagraph)
just removes that specific element from its container.