I want to polyfill the Element.matches
a method for IE.
I found these code on MDN:
if (!Element.prototype.matches) {
Element.prototype.matches =
Element.prototype.matchesSelector ||
Element.prototype.mozMatchesSelector ||
Element.prototype.msMatchesSelector ||
Element.prototype.oMatchesSelector ||
Element.prototype.webkitMatchesSelector ||
function(s) {
var matches = (this.document ||
this.ownerDocument).querySelectorAll(s),
i = matches.length;
while (--i >= 0 && matches.item(i) !== this) {}
return i > -1;
};
}
So I write some codes like:
function matches(node, selector) {
if (node.matches) {
return node.matches(selector)
}
const match = node.matchesSelector ||
node.webkitMatchesSelector ||
node.mozMatchesSelector ||
node.msMatchesSelector ||
node.oMatchesSelector ||
function (s) {
const matches = (node.ownerDocument || document).querySelectorAll(s)
let i = matches.length
while (--i >= 0 && matches[i] !== node) {}
return i > -1
}
return match(selector)
}
Though, I know this will work on most browsers except IE I deleted most of the code, and tested it for IE, this worked:
function match(node, selector) {
return node.msMatchesSelector(selector)
}
I wonder why this doesn't work:
function match(node, selector) {
var isMatch = node.msMatchesSelector
return isMatch(selector)
}