How to pass triggering element in addEventListener?

334 views Asked by At

I have this code:

window.onload = function(){ 
var player=0;
for(var i="0";i<"9";i++)
    document.getElementById(i).addEventListener("click",function(){oxfunc(document.getElementById(i))});
function oxfunc(s){
    s.innerHTML="!";    
}

The IDs of elements are numbered 0 to 8. I want to know which element was clicked. The above code is giving an error:

tictactoe.js:8 Uncaught TypeError: Cannot set property 'innerHTML' of null
    at oxfunc (tictactoe.js:8)
    at HTMLTableCellElement.<anonymous> (tictactoe.js:5)
oxfunc @ tictactoe.js:8
(anonymous) @ tictactoe.js:5
1

There are 1 answers

2
Quentin On BEST ANSWER

The triggering element will be this in the function, so you don't need to use your approach.

addEventListener("load", function() {
  var player = 0;
  for (var i = 0; i < 9; i++) {
    document.getElementById(i).addEventListener("click", function() {
      oxfunc(this);
    });
  }

  function oxfunc(s) {
    s.innerHTML = "!";
  }
});

If you want to use your approach, then see JavaScript closure inside loops – simple practical example.