Last active
October 18, 2021 08:09
-
-
Save toastal/c107bc8ce3516f45d5cc to your computer and use it in GitHub Desktop.
Tail-Recursive `Element.prototype.closest` Polyfill
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Element.matches() | |
* https://developer.mozilla.org/en-US/docs/Web/API/Element/matches | |
* The Element.matches() method returns true if the element would be selected | |
* by the specified selector string; otherwise, returns false. | |
* | |
* Prefixed Support: Android 2.2, Internet Explorer 9, Edge 12, Safari 5.0 | |
* Unprefixed Support: Chrome 34, Firefox 34, Safari 7.1, iOS Safari 8.0 | |
*/ | |
if (!("matches" in Element.prototype)) { | |
Element.prototype.matches = Element.prototype.msMatchesSelector | |
|| Element.prototype.webkitMatchesSelector; | |
} | |
/* | |
* Element.closest() | |
* https://developer.mozilla.org/en-US/docs/Web/API/Element/closest | |
* The Element.closest() method returns the closest ancestor of the current | |
* element (or the current element itself) which matches the selectors given in | |
* parameter. If there isn't such an ancestor, it returns null. | |
* | |
* Support: Chrome 41, Firefox 35, Safari 9.0 | |
*/ | |
if (!("closest" in Element.prototype)) { | |
Element.prototype.closest = function closest(selector) { | |
"use strict"; | |
return (function searchUpTree(selector, element) { | |
return element == null | |
? null | |
: element.matches(selector) | |
? element | |
: searchUpTree(selector, element.parentElement); | |
}(selector, this)); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment