3

I'm a beginner and i'm trying to do something easy to start with, i just want to be able to click on a div and when i click i will see the id of the div i clicked in the console. I can't figure out what's wrong with the code.

So basically, theres a div with 3 other div in it, i want to be able to click on each of them and depending on which one i clicked, receive the good id in the console.

I tried adding another console.log in the onclick to see if i was able to go into it at all but even that doesn't appear.

the "#parties" is the big div containing the 3 smaller div and the .partieind is the class given to those.

I have tried the querySelectorAll as well, but still nothing.

contPartie = document.querySelector("#parties");

console.log("just before onclick");
contPartie.querySelectorAll(".partieind").onclick = () => {
    console.log("in onclick");
    console.log(this.id);
}
  • 2
    Possible duplicate of [javascript adding click event listener to class](https://stackoverflow.com/questions/21700364/javascript-adding-click-event-listener-to-class) – ADyson Apr 10 '19 at 20:16

1 Answers1

3

There are two problems here:

You're using querySelectorAll. As @ADyson's referenced post pointed out, querySelectorAll returns a NodeList (an array-ish structure), so you can't directly assign .onclick = there. You have to loop through the list items and bind them separately, like this:

contPartie.querySelectorAll(".partieind").forEach(div => 
    div.onclick = () => {
      console.log("in onclick");
      console.log(this.id);
    }
}

And, in addition to that, notice the arrow function / this dichotomy here: Arrow functions lack this binding. You could fix that in two ways:

1) Replacing the arrow function syntax with good ol' classic function syntax (which binds this automatically):

contPartie.querySelectorAll(".partieind").forEach(div => 
    div.onclick = function() {
        console.log("in onclick");
        console.log(this.id);
    }
}

2) Accesing the div via the event argument passed to the handler:

contPartie.querySelectorAll(".partieind").forEach(div => 
    div.onclick = (e) => {
        console.log("in onclick");
        console.log(e.target.id);
    }
}

Notice I'm adding the e argument to the function, and using e.target to get the clicked div.

ezakto
  • 3,174
  • 22
  • 27