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.
Last active
September 12, 2015 19:14
-
-
Save petermac-/a132eed90e139e75be4b to your computer and use it in GitHub Desktop.
matchesSelector.js
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
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]') |
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
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment