Wednesday, November 14, 2018

[JavaScript][Exercise] Remove buttons by clicking button

An image gallery is a set of images with corresponding remove buttons. This is the HTML code for a gallery with two images:

<div class="image">
  <img src="https://goo.gl/kjzfbE" alt="First">
  <button class="remove">X</button>
</div>
<div class="image">
  <img src="https://goo.gl/d2JncW" alt="Second">
  <button class="remove">X</button>
</div>
Implement the setup function that registers a click event handler and implements the following logic: When the button of class remove is clicked, its parent <div> element should be removed from the gallery.

For example, after the first image has been removed from the gallery above, it's HTML code should look like this:

<div class="image">
  <img src="https://goo.gl/d2JncW" alt="Second">
  <button class="remove">X</button>
</div>
  
Referenced answer
Firstly we need to know how many image in gallery. Use a for-loop to add eventListener to related DOM, if click event is trigger, delete parentNode.
<html>
<body>
</body>
<script>
function setup() {
  var len = document.getElementsByClassName("remove").length;
  for(var i=0;i<len;i++){
      document.getElementsByClassName("remove")[i].addEventListener("click",function(){
        this.parentNode.remove();
      });
  }

}

// Example case.
document.body.innerHTML = `
<div class="image">
  <img src="https://goo.gl/kjzfbE" alt="First">
  <button class="remove">X</button>
</div>
<div class="image">
  <img src="https://goo.gl/d2JncW" alt="Second">
  <button class="remove">X</button>
</div>`;

setup();
console.log(document.body.innerHTML);
</script>
</html>
Beware this not work:
document.getElementsByClassName("remove")[i].click(function(){
    this.parentNode.remove();
});

Reference

https://stackoverflow.com/questions/40144638/how-to-remove-the-div-that-a-button-is-contained-in-when-the-button-is-clicked

No comments :

Post a Comment