3

I would like to find out if the method closest () is supported and if necessary (IE 11) use an alternative in the following form:

ancestor = ('closest' in document.documentElement) ? element.closest  (selector) : element.parentElement;

The consoles of my browsers (Edge, Chrome, Firefox, IE 11 - WIN 10) return 'true' or 'false' as expected.

Is this solution a clean solution or are there any pitfalls that I did not consider ?

Janek
  • 53
  • 5
  • Uh, if the method is not available, it doesn't use the `selector` but just get the parent element? So I wouldn't even consider this to be a "solution". – Bergi Aug 18 '19 at 20:00

2 Answers2

0

Better use a polyfill that checks if the methods exist and, if not, adds an equivalent to an Objects prototype. Then use the method in all browsers.

https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill

baao
  • 71,625
  • 17
  • 143
  • 203
0

Lets see what MDN says about this:

For browsers that do not support Element.closest(), but carry support for element.matches() (or a prefixed equivalent, meaning IE9+), a polyfill exists:

if (!Element.prototype.matches) {
  Element.prototype.matches = Element.prototype.msMatchesSelector || 
                              Element.prototype.webkitMatchesSelector;
}

if (!Element.prototype.closest) {
  Element.prototype.closest = function(s) {
    var el = this;

    do {
      if (el.matches(s)) return el;
      el = el.parentElement || el.parentNode;
    } while (el !== null && el.nodeType === 1);
    return null;
  };
}

so your approach is right. Please consult mdn for further info

alt255
  • 3,396
  • 2
  • 14
  • 20