2

When my page changes, the eventlisteners of elements with a certain classname should be added. There may be multiple Elements with this classname. The elements also have an attribute called taskNr. When clicked, the eventlistener function should delete an element with the id "task" + taskNr of the Element, the eventlistener is attached to.

I have tried to give the function a Parameter with the taskNr, but it changes to the taskNr of the last Element. That is why i now think about referring to taskNr from inside the function.

//fügt eventlistener für button removetask hinzu
function activateremovetasklistener(){
  var removeBtns = document.getElementsByClassName("fa fa-times-circle floatright fa-fw notfirst");
  for (i=0; i < removeBtns.length; i++) {
    var taskNr = removeBtns[i].getAttribute("taskNr");
    removeBtns[i].addEventListener("click", function(){
            removeTask(taskNr);
    })
  };    
}

//entfernt Task
function removeTask(tasknumber){
  var taskClass = document.getElementById("task" + tasknumber);
  taskClass.remove();
}

With this code it uses always the taskNr of the last element in removeBtns. It should use the one from removeBtns[i] (the element the eventlistener is attached to).

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
SarahK
  • 59
  • 1
  • 8

2 Answers2

2

The event object has details about where it was fired:

addEventListener("click", function(event){
    const element = event.currentTaget;
})

See also JavaScript closure inside loops – simple practical example which covers why your approach didn't work.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

Well you can always access the relevant element inside the click callback function using:

event.target || event.srcElement

Your code should be:

removeBtns[i].addEventListener("click", function(event){
    removeTask(event.target || event.srcElement);
})

function removeTask(element){
  element.remove();
}

You can check The Event interface MDN Reference for further details:

Event.srcElement

A non-standard alias (from old versions of Microsoft Internet Explorer) for Event.target, which is starting to be supported in some other browsers for web compatibility purposes.

Event.target

A reference to the target to which the event was originally dispatched.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
  • 1
    `target` could get a child element (e.g. if there was a span inside the button) and is best avoided. – Quentin Jul 26 '19 at 09:05
  • 1
    @Quentin I just used `.target` and `.srcElement` for browser compatibility purpose only. – cнŝdk Jul 26 '19 at 09:10