<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>Beware this not work:
<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>
document.getElementsByClassName("remove")[i].click(function(){
this.parentNode.remove();
});
No comments :
Post a Comment