I have a table with id "tbl" and it has 2 rows and 3 cols. Each cell(td) has an explicitly defined id. Also, the table has an onclick event that calls a function foo(). The onclick() would be generated whenever any cell is clicked. The table tag is
< table id="tbl" width="80%" height="20%" onclick="javascript: foo()" >
I also tried javascript:foo(this)
I want to find out the id of the table cell that was clicked.
I have tried the following javascript
function foo(e)
{
var sender = (e && e.target) || (window.event && window.event.srcElement);
alert("Sender" + sender.id);
}
This works great in Google Chrome and IE, but not in Firefox. In Firefox, sender is undefined. How to get the caller cell in Firefox?
caller property of the JavaScript function object returns the function that invoked the specified function. It returns null if the function “f” was invoked by the top-level code in JavaScript. For functions like strict functions, async functions and generator function this method returns null.
The getElementById() method returns an element with a specified value. The getElementById() method returns null if the element does not exist. The getElementById() method is one of the most common methods in the HTML DOM. It is used almost every time you want to read or edit an HTML element.
Document.getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.
A call stack is a mechanism for an interpreter (like the JavaScript interpreter in a web browser) to keep track of its place in a script that calls multiple functions — what function is currently being run and what functions are called from within that function, etc.
Firstly, remove javascript:
from the onclick
attribute. You're confusing this with javascript in the href
attribute of a link. In Javascript code, javascript:
would create a label named "javascript".
Other than that, foo(event)
should work correctly with your final JavaScript code sample. The reason it doesn't work in Firefox but does in Chrome and IE is; they both support the global event object, window.event
(which is evaluated when your e.target
yields undefined
, because this
is an element which will not have a target
property). Firefox doesn't support the global event
object.
Further reading:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With