dom.ts 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // Node.closest() polyfill
  2. if ('Element' in window && !Element.prototype.closest) {
  3. Element.prototype.closest = function(this: any, s) {
  4. const matches = (this.document || this.ownerDocument).querySelectorAll(s);
  5. let el = this;
  6. let i;
  7. // eslint-disable-next-line
  8. do {
  9. i = matches.length;
  10. // eslint-disable-next-line
  11. while (--i >= 0 && matches.item(i) !== el) {}
  12. el = el.parentElement;
  13. } while (i < 0 && el);
  14. return el;
  15. };
  16. }
  17. export function getPreviousCousin(node, selector) {
  18. let sibling = node.parentElement.previousSibling;
  19. let el;
  20. while (sibling) {
  21. el = sibling.querySelector(selector);
  22. if (el) {
  23. return el;
  24. }
  25. sibling = sibling.previousSibling;
  26. }
  27. return undefined;
  28. }
  29. export function getNextCharacter(global = window) {
  30. const selection = global.getSelection();
  31. if (!selection.anchorNode) {
  32. return null;
  33. }
  34. const range = selection.getRangeAt(0);
  35. const text = selection.anchorNode.textContent;
  36. const offset = range.startOffset;
  37. return text.substr(offset, 1);
  38. }