create-dom.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. "use strict";
  2. /**
  3. * 创建DOM 节点
  4. * @param {String} str Dom 字符串
  5. * @return {HTMLElement} DOM 节点
  6. */
  7. Object.defineProperty(exports, "__esModule", { value: true });
  8. var TABLE;
  9. var TABLE_TR;
  10. var FRAGMENT_REG;
  11. var CONTAINERS;
  12. function initConstants() {
  13. TABLE = document.createElement('table');
  14. TABLE_TR = document.createElement('tr');
  15. FRAGMENT_REG = /^\s*<(\w+|!)[^>]*>/;
  16. CONTAINERS = {
  17. tr: document.createElement('tbody'),
  18. tbody: TABLE,
  19. thead: TABLE,
  20. tfoot: TABLE,
  21. td: TABLE_TR,
  22. th: TABLE_TR,
  23. '*': document.createElement('div'),
  24. };
  25. }
  26. function createDom(str) {
  27. if (!TABLE) {
  28. initConstants();
  29. }
  30. var name = FRAGMENT_REG.test(str) && RegExp.$1;
  31. if (!name || !(name in CONTAINERS)) {
  32. name = '*';
  33. }
  34. var container = CONTAINERS[name];
  35. str = typeof str === 'string' ? str.replace(/(^\s*)|(\s*$)/g, '') : str;
  36. container.innerHTML = '' + str;
  37. var dom = container.childNodes[0];
  38. if (dom && container.contains(dom)) {
  39. container.removeChild(dom);
  40. }
  41. return dom;
  42. }
  43. exports.default = createDom;
  44. //# sourceMappingURL=create-dom.js.map