When I run event.path[n].id
in Firefox, I get this error. It works in other browsers.
event.path undefined
When I run event.path[n].id
in Firefox, I get this error. It works in other browsers.
event.path undefined
The path
property of Event
objects is non-standard. The standard equivalent is the composedPath
method. But it was new when the question was asked (2016); it's well-established as of this update in January 2023.
So you may want to try composedPath
and fall back to path
(or just use composedPath
now it's established):
// Written in ES5 for compatibility with browsers that weren't obsolete
// yet when the question was posted, although they are now
var path = event.composedPath ? event.composedPath() : event.path;
if (path) {
// You got some path information
} else {
// This browser doesn't supply path information
}
Obviously that won't give you path information if the browser doesn't supply it, but it allows for both the old way and the new, standard way, and so will do its best cross-browser.
Example:
// Written in ES5 for compatibility with browsers that weren't obsolete
// yet when the question was posted, although they are now
document.getElementById(target).addEventListener(click, function (e) {
// Just for demonstration purposes
if (e.path) {
if (e.composedPath) {
console.log(Supports `path` and `composedPath`);
} else {
console.log(Supports `path` but not `composedPath`);
}
} else if (e.composedPath) {
console.log(Supports `composedPath` (but not `path`));
} else {
console.log(Supports neither `path` nor `composedPath`);
}
// Per the above, get the path if we can, first using the standard
// method if possible, falling back to non-standard `path`
var path = event.composedPath ? event.composedPath() : event.path;
// Show it if we got it
if (path) {
console.log(Path ( + path.length + ));
Array.prototype.forEach.call(path, function(entry) {
console.log(entry === window ? window : entry.nodeName);
});
}
});
.as-console-wrapper {
max-height: 100% !important;
}
<div id=target>Click me</div>
According to MDN, all major browsers support composedPath
as of January 2023. Chrome (and other Chromium-based browsers) supported both path
(it was a Chrome innovation) and composedPath
until v109 when path
was removed. (The obsolete browsers IE11 and Legacy Edge [Microsoft Edge prior to v79 when it became a Chromium-based browser] didn't support either of them.)
If you ran into a browser that doesn't support either of them, I don't think you can get the path information as of when the event was triggered. You can get the path via e.target.parentNode
and each subsequent parentNode
, which is usually the same, but of course the point of composedPath
is that it's not always the same (if something modifies the DOM after the event was triggered but before your handler got called).