0

I tried to check out other answers on Stackoverflow and apply it to my own code but I couldn't get it to work.

I'm trying to 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 element should be removed from the list. It should be in pure javascript.

This is the original code:

function setup() {
//write your code here  

}

document.body.innerTML = `
<div class="image">
    <img src="https://" alt="First">
    <button class="remove">X</button>
</div>
<div class="image">
    <img src="https://" alt="Second">
    <button class="remove">X</button>
</div>`;

setup();

document.getElementsByClassName("remove")[0].click();
console.log(document.body.innerHTML);

Here's my attempt

function setup() {
  
  let buttondel = document.getElementsByClassName("remove");
  
  buttondel.addEventListener('click',function(e){
    e.currentTarget.parentNode.remove();
  })
}

but I'm getting this error "buttondel.addEventListener is not a function". Here's my code at Codepen: https://codepen.io/kikibres/pen/PoZLbZa?editors=1011

Kristina Bressler
  • 1,642
  • 1
  • 25
  • 60
  • 1
    `getElementsByClassName` returns a HTMLCollection, not a single element. You either need to grab the first element, use a different selector method like `querySelector()` or iterate through the collection and add event listeners to each element. – Nick Parsons Jul 24 '20 at 03:20
  • Hi. Can you take a look at my code again, please? I updated my code, but I got an error, "Cannot read property 'click' of undefined " in the console.... – Kristina Bressler Jul 24 '20 at 04:30
  • You have a typo: `innerTML` should be: `innerHTML` – Nick Parsons Jul 24 '20 at 04:40

1 Answers1

1

You can make a "querySelectorAll" to get all buttons with the class remove, and then after that you can use forEach, or even a normal For loop to add the event listener of this.parentNode.remove().

Here is a codepen to help you understand:

https://codepen.io/marcoamorim95/pen/JjGZpzR

arrayBtns = document.querySelectorAll('.remove');

arrayBtns.forEach(btn => {
  btn.addEventListener('click', function() {
    this.parentNode.remove();
  })
})