How do I remove the parent element and all its contents when child element is clicked?

3

In this tag, how could I remove the <li> (parent) element whenever the <a> (child) element is clicked? Remembering I want to do this without jQuery.

<ul>
   <li>
      <a href="#">example</a>
   </li>
   <li>
      <a href="#">example</a>
   </li>
</ul>
    
asked by anonymous 10.02.2015 / 00:04

1 answer

4

You need to merge an event dropper into these a elements and then use .parentNode to find out what li element you are looking for.

You will still have to call .parentNode of this li because the javascript API needs to know the parent: elementoPai.removeChild(filho); .

That is:

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: link

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>
    
10.02.2015 / 00:09