Skip to content

Instantly share code, notes, and snippets.

@petermac-
Last active September 12, 2015 19:14
Show Gist options
  • Save petermac-/a132eed90e139e75be4b to your computer and use it in GitHub Desktop.
Save petermac-/a132eed90e139e75be4b to your computer and use it in GitHub Desktop.
matchesSelector.js
function matchesSelector(el, selector) {
var p = Element.prototype;
var f = p.matches || p.webkitMatchesSelector || p.mozMatchesSelector || p.msMatchesSelector || function(s) {
return [].indexOf.call(document.querySelectorAll(s), this) !== -1;
};
return f.call(el, selector);
}
// Usage
matchesSelector(document.getElementById('myDiv'), 'div.someSelector[some-attribute=true]')
function matchesSelector(el, selector) {
var p = Element.prototype;
var f = p.matches || p.webkitMatchesSelector || p.mozMatchesSelector || p.msMatchesSelector || function(s) {
return [].indexOf.call(this.parentNode.querySelectorAll(s), this) !== -1;
};
return f.call(el, selector);
}

Often times we validate input before moving forward; ensuring a truthy value, ensuring forms data is valid, etc. But how often do we ensure an element qualifies for moving forward?
You can use a matchesSelector function to validate if an element is of a given selector match.

http://davidwalsh.name/essential-javascript-functions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment