dom.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. const range = document.createRange();
  2. export function parseHTML(html) {
  3. return range.createContextualFragment(html);
  4. }
  5. // equivalent to jQuery's :visble
  6. export function isVisible(el) {
  7. return !!(el.offsetWidth || el.offsetHeight || el.getClientRects().length);
  8. }
  9. export function hideElement(el) {
  10. if (el.style.display === 'none') {
  11. return;
  12. }
  13. // back up the existing display setting in data-style-display
  14. if (el.style.display) {
  15. el.dataset.styleDisplay = el.style.display;
  16. }
  17. el.style.display = 'none';
  18. }
  19. export function showElement(el) {
  20. if (el.style.display !== 'none') {
  21. return;
  22. }
  23. if (el.dataset.styleDisplay) {
  24. // restore backed-up dispay property
  25. el.style.display = el.dataset.styleDisplay;
  26. delete el.dataset.styleDisplay;
  27. } else {
  28. el.style.display = '';
  29. }
  30. }
  31. export function emptyChildNodes(el) {
  32. if (el.firstChild) {
  33. el.removeChild(el.firstChild);
  34. emptyChildNodes(el);
  35. }
  36. }
  37. export function replaceChildNodes(el, newChildNodes) {
  38. emptyChildNodes(el);
  39. if (newChildNodes instanceof DocumentFragment) {
  40. el.appendChild(newChildNodes);
  41. } else if (typeof newChildNodes === 'string') {
  42. el.appendChild(parseHTML(newChildNodes));
  43. } else if (typeof newChildNodes.forEach === 'function') {
  44. newChildNodes.forEach((node) => {
  45. el.appendChild(node);
  46. });
  47. }
  48. }