idrefs.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import getRootNode from './get-root-node';
  2. import { tokenList } from '../../core/utils';
  3. /**
  4. * Get elements referenced via a space-separated token attribute;
  5. * it will insert `null` for any Element that is not found
  6. * @method idrefs
  7. * @memberof axe.commons.dom
  8. * @instance
  9. * @param {HTMLElement} node
  10. * @param {String} attr The name of attribute
  11. * @return {Array|null} Array of elements (or `null` if not found)
  12. *
  13. * NOTE: When in a shadow DOM environment: ID refs (even for slotted content)
  14. * refer to the document in which the element is considered to be in the
  15. * "light DOM". Therefore, we use getElementById on the root node and not QSA
  16. * on the flattened tree to dereference idrefs.
  17. *
  18. */
  19. function idrefs(node, attr) {
  20. node = node.actualNode || node;
  21. try {
  22. const doc = getRootNode(node);
  23. const result = [];
  24. let attrValue = node.getAttribute(attr);
  25. if (attrValue) {
  26. attrValue = tokenList(attrValue);
  27. for (let index = 0; index < attrValue.length; index++) {
  28. result.push(doc.getElementById(attrValue[index]));
  29. }
  30. }
  31. return result;
  32. } catch (e) {
  33. throw new TypeError('Cannot resolve id references for non-DOM nodes');
  34. }
  35. }
  36. export default idrefs;