Skip to content

Commit

Permalink
Simplify closest polyfill
Browse files Browse the repository at this point in the history
1. It should not secretly polyfill .matches
2. It now uses MDN's polyfill https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill
3. Drops test that no longer necessary

Signed-off-by: Federico Brigante <github@bfred.it>
  • Loading branch information
fregante committed Mar 7, 2019
1 parent 26f0151 commit 2d54c11
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 32 deletions.
28 changes: 10 additions & 18 deletions src/closest.js
@@ -1,17 +1,11 @@
var DOCUMENT_NODE_TYPE = 9;

/**
* A polyfill for Element.matches()
* Local polyfills for Element.matches() and Element.closest()
*/
if (typeof Element !== 'undefined' && !Element.prototype.matches) {
var proto = Element.prototype;

proto.matches = proto.matchesSelector ||
proto.mozMatchesSelector ||
proto.msMatchesSelector ||
proto.oMatchesSelector ||
proto.webkitMatchesSelector;
}
var matches = Element.prototype.matches ||
Element.prototype.msMatchesSelector ||
Element.prototype.webkitMatchesSelector;


/**
* Finds the closest parent that matches a selector.
Expand All @@ -21,13 +15,11 @@ if (typeof Element !== 'undefined' && !Element.prototype.matches) {
* @return {Function}
*/
function closest (element, selector) {
while (element && element.nodeType !== DOCUMENT_NODE_TYPE) {
if (typeof element.matches === 'function' &&
element.matches(selector)) {
return element;
}
element = element.parentNode;
}
do {
if (matches.call(element, selector)) return element;
element = element.parentElement || element.parentNode;
} while (element !== null && element.nodeType === 1);
return null;
}

module.exports = closest;
14 changes: 0 additions & 14 deletions test/closest.js
Expand Up @@ -28,18 +28,4 @@ describe('closest', function() {
it('should return itself if the same selector is passed', function() {
assert.ok(closest(document.body, 'body'), document.body);
});

it('should not throw on elements without matches()', function() {
var fakeElement = {
nodeType: -1, // anything but DOCUMENT_NODE_TYPE
parentNode: null,
matches: undefined // undefined to emulate Elements without this function
};

try {
closest(fakeElement, '#a')
} catch (err) {
assert.fail();
}
});
});

0 comments on commit 2d54c11

Please sign in to comment.