find-up-virtual.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { matchesSelector } from '../../core/utils';
  2. /**
  3. * recusively walk up the DOM, checking for a node which matches a selector
  4. *
  5. * **WARNING:** this should be used sparingly, as it's not even close to being performant
  6. * @method findUpVirtual
  7. * @memberof axe.commons.dom
  8. * @instance
  9. * @deprecated use axe.utils.closest
  10. * @param {VirtualNode} element The starting virtualNode
  11. * @param {String} target The selector for the HTMLElement
  12. * @return {HTMLElement|null} Either the matching HTMLElement or `null` if there was no match
  13. */
  14. function findUpVirtual(element, target) {
  15. let parent;
  16. parent = element.actualNode;
  17. // virtualNode will have a shadowId if the element lives inside a shadow DOM or is
  18. // slotted into a shadow DOM
  19. if (!element.shadowId && typeof element.actualNode.closest === 'function') {
  20. // non-shadow DOM elements
  21. const match = element.actualNode.closest(target);
  22. if (match) {
  23. return match;
  24. }
  25. return null;
  26. }
  27. // handle shadow DOM elements and older browsers
  28. do {
  29. // recursively walk up the DOM, checking each parent node
  30. parent = parent.assignedSlot ? parent.assignedSlot : parent.parentNode;
  31. if (parent && parent.nodeType === 11) {
  32. parent = parent.host;
  33. }
  34. } while (
  35. parent &&
  36. !matchesSelector(parent, target) &&
  37. parent !== document.documentElement
  38. );
  39. if (!parent) {
  40. return null;
  41. }
  42. if (!matchesSelector(parent, target)) {
  43. return null;
  44. }
  45. return parent;
  46. }
  47. export default findUpVirtual;