hw_15_01_HTML_Tree.html 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <header>
  2. HTML Tree
  3. </header>
  4. <body>
  5. <script>
  6. function walker(parent) {
  7. let str = "";
  8. let tagName = parent.tagName;
  9. if (tagName) {
  10. str = `<${tagName}`;
  11. let attrs = parent.attrs;
  12. if (attrs) {
  13. for (const attrName in attrs) {
  14. str += ` ${attrName}=${attrs[attrName]}`;
  15. }
  16. }
  17. str += '>';
  18. for (const child of parent.children) {
  19. str += walker(child) //вложенный вызов - вложенный уровень вложенности :-D
  20. }
  21. str += `</${tagName}>`;
  22. }
  23. else {
  24. str = parent;
  25. }
  26. return str;
  27. }
  28. const table = {
  29. tagName: 'table',
  30. attrs: {
  31. border: "1",
  32. },
  33. children: [
  34. {
  35. tagName: 'tr',
  36. children: [
  37. {
  38. tagName: "td",
  39. children: ["1x1"],
  40. },
  41. {
  42. tagName: "td",
  43. children: ["1x2"],
  44. },
  45. ]
  46. },
  47. {
  48. tagName: 'tr',
  49. children: [
  50. {
  51. tagName: "td",
  52. children: ["2x1"],
  53. },
  54. {
  55. tagName: "td",
  56. children: ["2x2"],
  57. },
  58. ]
  59. }
  60. ]
  61. }
  62. document.write(walker(table)); //вернет <table border='1' ....
  63. </script>
  64. </body>