89

When I run event.path[n].id in Firefox, I get this error. It works in other browsers.

event.path undefined

0

5 Answers 5

180

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).

12
  • Hey! Thank you for your answer, but event.ComposedPath returned undefined in Chrome and Firefox
    – Hanson
    Commented Aug 31, 2016 at 11:14
  • 1
    It seems FF has support for composedPath() now (tested with version 59.0.3). Commented May 14, 2018 at 11:14
  • 1
    @PeterHerdenborg - Indeed! I've updated. Chrome does too now (it used to support only path). Also tested Edge, was sorry to see neither is supported. Commented May 14, 2018 at 11:23
  • 2
    @Esger - No, composed is something else entirely, unrelated to path or composedPath(). Commented Dec 3, 2018 at 10:50
  • 1
    Chrome has just removed event.path too (from 109) chromestatus.com/feature/5726124632965120 Commented Jan 30, 2023 at 23:05
27

You can create your own composedPath function if it's not implemented in the browser:

function composedPath (el) {

    var path = [];

    while (el) {

        path.push(el);

        if (el.tagName === 'HTML') {

            path.push(document);
            path.push(window);

            return path;
       }

       el = el.parentElement;
    }
}

The returned value is equivalent to event.path of Google Chrome.

Example:

document.getElementById('target').addEventListener('click', function(event) {

    var path = event.path || (event.composedPath && event.composedPath()) || composedPath(event.target);
});
4
  • 6
    That's is not actually the same, sometimes the parentElement is returning null is some cases and the event.path/composePath() will give you the full path..
    – user3482773
    Commented Dec 26, 2017 at 14:51
  • 2
    This is not an implementation of path/composedPath. It misses the key aspect of them (which you can't polyfill). Commented May 14, 2018 at 11:24
  • The accepted answer misses this function to work on edge, since composed path is not supported either. Really nice.
    – Cédric
    Commented Jan 16, 2019 at 8:26
  • this does not work in open shadow roots. I was looking for a Edge polyfill that would give me the source dom node within the web component, not the document. Commented Jun 27, 2019 at 9:45
12

This function serves as a polyfill for Event.composedPath() or Event.Path

function eventPath(evt) {
    var path = (evt.composedPath && evt.composedPath()) || evt.path,
        target = evt.target;

    if (path != null) {
        // Safari doesn't include Window, but it should.
        return (path.indexOf(window) < 0) ? path.concat(window) : path;
    }

    if (target === window) {
        return [window];
    }

    function getParents(node, memo) {
        memo = memo || [];
        var parentNode = node.parentNode;

        if (!parentNode) {
            return memo;
        }
        else {
            return getParents(parentNode, memo.concat(parentNode));
        }
    }

    return [target].concat(getParents(target), window);
}
1
  • 1
    I've tested this approach and everything works like a charm! Commented Apr 29, 2021 at 7:33
5

Use composePath() and use a polyfill for IE: https://gist.github.com/rockinghelvetica/00b9f7b5c97a16d3de75ba99192ff05c

include above file or paste code:

// Event.composedPath
(function(e, d, w) {
  if(!e.composedPath) {
    e.composedPath = function() {
      if (this.path) {
        return this.path;
      } 
    var target = this.target;

    this.path = [];
    while (target.parentNode !== null) {
      this.path.push(target);
      target = target.parentNode;
    }
    this.path.push(d, w);
    return this.path;
    }
  }
})(Event.prototype, document, window);

and then use:

var path = event.path || (event.composedPath && event.composedPath());
1
  • This polyfill does not handle all cases. Especially when target is null. Consider the following scenario: const image = new Image(); image.onload = (e) => { // Here event.target is null console.log("path = ", e.composedPath()) // fire error } Commented Apr 12, 2023 at 15:05
1

I had the same issue. I need the name of the HTML element. In Chrome I get the name with path. In Firefox I tried with composedPath, but it returns a different value.

For solving my problem, I used e.target.nodeName. With target function you can retrieve the HTML element in Chrome, Firefox and Safari.

This is my function in Vue.js:

selectFile(e) {
        this.nodeNameClicked = e.target.nodeName
        if (this.nodeNameClicked === 'FORM' || this.nodeNameClicked === 'INPUT' || this.nodeNameClicked === 'SPAN') {
          this.$refs.singlefile.click()
      }
    }
1
  • A small improvement here - you can check for multiple values using an array: if (['FORM', 'INPUT', 'SPAN'].indexOf(this.nodeNameClicked) !== -1) {} Commented Jan 6, 2023 at 16:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.