2

I am trying to delete <p> node including it's all children when the <span> is clicked. The <span> is located inside the <p>.

The HTML example is:

<p>Hello World!<span>x</span></p>

I want to achieve this with JavaScript not jQuery.

My code is:

spancomment.addEventListener('click', deleteComment(this), false);
function deleteComment(e) {
    e.parentNode.parentNode.parentNode.removeChild(e.parentNode.parentNode);
}

I get the following error:

TypeError: undefined is not an object (evaluating 'e.parentNode.parentNode')

I followed: How to remove the parent element using plain JavaScript?

Community
  • 1
  • 1
Maihan Nijat
  • 9,054
  • 11
  • 62
  • 110

1 Answers1

3

Try to pass the function reference as a event handler,

spancomment.addEventListener('click', deleteComment, false);
function deleteComment(e) {
    this.parentNode.remove();
}

Also you can simply use .remove() over the parent node.

DEMO

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130