hw_15_02_DOM_Tree.html 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <header>
  2. DOM Tree
  3. </header>
  4. <body>
  5. <script>
  6. function walker(parent) {
  7. let res = undefined;
  8. let tagName = parent.tagName;
  9. if (tagName) {
  10. res = document.createElement(tagName);
  11. let attrs = parent.attrs;
  12. if (attrs) {
  13. for (const attrName in attrs) {
  14. res[attrName] = attrs[attrName];
  15. }
  16. }
  17. for (const child of parent.children) {
  18. let childRes = walker(child)
  19. if (typeof childRes === "object") {
  20. res.append(childRes);
  21. }
  22. else {
  23. res.innerText = childRes;
  24. }
  25. }
  26. }
  27. else {
  28. res = parent;
  29. }
  30. return res;
  31. }
  32. const table = {
  33. tagName: 'table',
  34. attrs: {
  35. border: "1",
  36. },
  37. children: [
  38. {
  39. tagName: 'tr',
  40. children: [
  41. {
  42. tagName: "td",
  43. children: ["1x1"],
  44. },
  45. {
  46. tagName: "td",
  47. children: ["1x2"],
  48. },
  49. ]
  50. },
  51. {
  52. tagName: 'tr',
  53. children: [
  54. {
  55. tagName: "td",
  56. children: ["2x1"],
  57. },
  58. {
  59. tagName: "td",
  60. children: ["2x2"],
  61. },
  62. ]
  63. }
  64. ]
  65. }
  66. document.body.append(walker(table)); //вернет <table border='1' ....
  67. </script>
  68. </body>