getParents.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /**
  2. * Get all DOM element up the tree that contain a class, ID, or data attribute
  3. * @param {Node} elem The base element
  4. * @param {String} selector The class, id, data attribute, or tag to look for
  5. * @return {Array} Null if no match
  6. */
  7. var getParents = function (elem, selector) {
  8. var parents = [];
  9. var firstChar;
  10. if (selector) {
  11. firstChar = selector.charAt(0);
  12. }
  13. // Get matches
  14. for (; elem && elem !== document; elem = elem.parentNode) {
  15. if (selector) {
  16. // If selector is a class
  17. if (firstChar === '.') {
  18. if (elem.classList.contains(selector.substr(1))) {
  19. parents.push(elem);
  20. }
  21. }
  22. // If selector is an ID
  23. if (firstChar === '#') {
  24. if (elem.id === selector.substr(1)) {
  25. parents.push(elem);
  26. }
  27. }
  28. // If selector is a data attribute
  29. if (firstChar === '[') {
  30. if (elem.hasAttribute(selector.substr(1, selector.length - 1))) {
  31. parents.push(elem);
  32. }
  33. }
  34. // If selector is a tag
  35. if (elem.tagName.toLowerCase() === selector) {
  36. parents.push(elem);
  37. }
  38. } else {
  39. parents.push(elem);
  40. }
  41. }
  42. // Return parents if any exist
  43. if (parents.length === 0) {
  44. return null;
  45. } else {
  46. return parents;
  47. }
  48. };