Guest User

Untitled

a guest
Nov 13th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.68 KB | None | 0 0
  1. GetClosest = function (elem, selector) {
  2.  
  3. for (; elem && elem !== document.body; elem = elem.parentNode) {
  4.  
  5. // If the elem matches at first iteration.
  6. if(elem.matches(selector)) {
  7.  
  8. return elem;
  9.  
  10. } else {
  11.  
  12. // Scans all the childs of current iterated element (always higher in DOM until found).
  13. // If one matches the selector it'll stop and return it.
  14. child = elem.parentNode.firstChild;
  15. do {
  16.  
  17. if(child.nodeType === 3) continue; // text node
  18. if(child.matches(selector)) return child;
  19.  
  20. } while (child = child.nextElementSibling);
  21. }
  22. }
  23.  
  24. return null;
  25.  
  26. };
Add Comment
Please, Sign In to add comment