Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix: document.querySelector("").onclick() not working

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);
}
like image 844
Marylène Beaudin Avatar asked Mar 13 '26 19:03

Marylène Beaudin


1 Answers

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.

like image 149
ezakto Avatar answered Mar 16 '26 15:03

ezakto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!