dom.ts 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // Node.closest() polyfill
  2. if ('Element' in window && !Element.prototype.closest) {
  3. Element.prototype.closest = function(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. } while (i < 0 && (el = el.parentElement));
  13. return el;
  14. };
  15. }
  16. export function getPreviousCousin(node, selector) {
  17. let sibling = node.parentElement.previousSibling;
  18. let el;
  19. while (sibling) {
  20. el = sibling.querySelector(selector);
  21. if (el) {
  22. return el;
  23. }
  24. sibling = sibling.previousSibling;
  25. }
  26. return undefined;
  27. }
  28. export function getNextCharacter(global = window) {
  29. const selection = global.getSelection();
  30. if (!selection.anchorNode) {
  31. return null;
  32. }
  33. const range = selection.getRangeAt(0);
  34. const text = selection.anchorNode.textContent;
  35. const offset = range.startOffset;
  36. return text.substr(offset, 1);
  37. }