简体   繁体   中英

Pure JavaScript: Remove Element when it's child is clicked

I have:

<ul id="list">
  <li>Some text <span class="removeParent">X</span></li>
</ul>

And when the span.removeParent is clicked, li have to be deleted.

It's very simple but the only (unfortunately working) solution I came up with was:

span.addEventListener("click", this.parentElement.parentElement.removeChild(this.parentElement);

It may be out of context so here's the link to the full to-do app: https://jsfiddle.net/w246hn3b/3/

I'm not sure if

this.parentElement.parentElement.removeChild(this.parentElement);

is the best, most efficient solution

This is a great use case for event delegation. Since the click event will bubble up the DOM to the parent node, you can listen for the click event on the root ancestor, and then check to see if the clicked element matches your target type.

 var todolist = document.getElementById('todolist'); todolist.addEventListener('click', function(e){ if(e.target.matches('.remove')){ todolist.removeChild(e.target.parentNode); } }); 
 .remove { color: #821818; display: inline-block; padding: 3px 10px; border: 1px solid #d84c4c; border-radius: 2px; cursor: pointer; position: absolute; right: 0px; top: 0px; height: 100%; box-sizing: border-box; background: #f1bbc0; font-weight: 700; font-size: 25px; } #todolist{ list-style:none; } #todolist li{ display:block; position:relative; padding:8px 6px; width:300px; margin:5px 0px; border-radius:2px; box-shadow: 0 3px 4px 0 rgba(0, 0, 0, 0.14), 0 1px 8px 0 rgba(0, 0, 0, 0.12), 0 3px 3px -2px rgba(0, 0, 0, 0.4); } 
 <ul id='todolist'> <li>1<span class='remove'>&times;</span></li> <li>2<span class='remove'>&times;</span></li> <li>3<span class='remove'>&times;</span></li> <li>4<span class='remove'>&times;</span></li> <li>5<span class='remove'>&times;</span></li> <li>6<span class='remove'>&times;</span></li> <li>7<span class='remove'>&times;</span></li> <li>8<span class='remove'>&times;</span></li> </ul> 

some resources on event delegation: https://gomakethings.com/why-event-delegation-is-a-better-way-to-listen-for-events-in-vanilla-js/

https://davidwalsh.name/event-delegate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM