index.js 1007 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. 'use strict';
  2. /**
  3. * Determine if a DOM element matches a CSS selector
  4. *
  5. * @param {Element} elem
  6. * @param {String} selector
  7. * @return {Boolean}
  8. * @api public
  9. */
  10. function matches(elem, selector) {
  11. // Vendor-specific implementations of `Element.prototype.matches()`.
  12. var proto = window.Element.prototype;
  13. var nativeMatches = proto.matches ||
  14. proto.mozMatchesSelector ||
  15. proto.msMatchesSelector ||
  16. proto.oMatchesSelector ||
  17. proto.webkitMatchesSelector;
  18. if (!elem || elem.nodeType !== 1) {
  19. return false;
  20. }
  21. var parentElem = elem.parentNode;
  22. // use native 'matches'
  23. if (nativeMatches) {
  24. return nativeMatches.call(elem, selector);
  25. }
  26. // native support for `matches` is missing and a fallback is required
  27. var nodes = parentElem.querySelectorAll(selector);
  28. var len = nodes.length;
  29. for (var i = 0; i < len; i++) {
  30. if (nodes[i] === elem) {
  31. return true;
  32. }
  33. }
  34. return false;
  35. }
  36. /**
  37. * Expose `matches`
  38. */
  39. module.exports = matches;