create-dom.js 1.1 KB

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