How to remove the parent element and all its content when child element is clicked?

Asked

Viewed 1,077 times

3

In that marking, how could I remove the element <li> (parent) whenever the <a> (son) is clicked? Remembering that I want to do it without jQuery.

<ul>
   <li>
      <a href="#">example</a>
   </li>
   <li>
      <a href="#">example</a>
   </li>
</ul>

1 answer

4

You need to attach an event receiver to those elements a and then use the .parentNode to know what the element is li you seek.

You’re gonna have to call .parentNode that li because the javascript API needs to know father and son: elementoPai.removeChild(filho);.

That is to say:

var links = document.querySelectorAll('a'); 
for (var i = 0; i<links.length; i++){
    links[i].addEventListener('click', removerPai);
}

function removerPai(e){
    e.preventDefault();
    var li = this.parentNode;
    li.parentNode.removeChild(li);
}

jsFiddle: http://jsfiddle.net/kxpwuLem/

var links = document.querySelectorAll('a'); 
for (var i = 0; i<links.length; i++){
    links[i].addEventListener('click', removerPai);
}

function removerPai(e){
    e.preventDefault();
    var li = this.parentNode;
    li.parentNode.removeChild(li);
}
<ul>
   <li>
      <a href="#">example</a>
   </li>
   <li>
      <a href="#">example</a>
   </li>
</ul>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.