You can't use string concatenation meaningfully with a DOM element, so this is incorrect:
cell.setAttribute("onclick", 'clickHandler('+cell+');');
Moreover, there's no reason whatsoever to use a string for this. If you want to use "simplistic" event handling, assign a function to the onclick
property:
cell.onclick = clickHandler;
To use modern event handling, use addEventListener
:
cell.addEventListener(clickHandler);
Sadly, old IE (or IE in "pretend to be old and useless" mode, aka "compatibility mode) doesn't have addEventListener
and you have to use attachEvent
instead; see this answer if you need to support old IE / useless IE.
(Another alternative below.)
In either case, when the handler is called, the cell you added the handler to is available via this
, so:
function clickHandler() {
console.log(this.id);
}
It's also available via the currentTarget
property of the event object you receive, so this also works:
function clickHandler(e) {
console.log(e.currentTarget.id);
}
(There's also e.target
, which is where the event originated — so for instance, if you had <td id="foo"><span>click me</span></td>
and hooked click
on the td
, if you click the span
then this
and e.currentTarget
refer to the td
and e.target
refers to the span
.)
But another alternative for you is to not hook click
on each and every td
, but instead hook it on the table
and then work from e.target
:
table.addEventListener("click", clickHandler);
and
function clickHandler(e) {
var td = e.target;
while (td.tagName != "TD") {
td = td.parentNode;
if (!td || td == this) {
return; // Click didn't pass through a td
}
}
console.log(td.id);
}
Side note: As you can see above, id
is a reflected property for the id
attribute, so you can set the id
using the property as well:
cell.id = k + "," + l;
Also note that the "" +
and + ""
on the original version of that line are completely unnecesary; if you use +
on a number and string, it does string concatenation, not addition, regardless of the order of the operands.