hw_15_04_string.html 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 = '{';
  11. str += `"tagName":"${tagName}",`;
  12. let attrs = parent.attrs;
  13. if (attrs) {
  14. str += '"attrs":{';
  15. let attrsArr = [];
  16. for (const attrName in attrs) {
  17. attrsArr.push(`"${attrName}":"${attrs[attrName]}"`);
  18. }
  19. str += attrsArr.join(',');
  20. str += '},';
  21. }
  22. if (parent.children) {
  23. str += '"children":['
  24. let childrenArr = [];
  25. for (const child of parent.children) {
  26. childrenArr.push(walker(child)); //вложенный вызов - вложенный уровень вложенности :-D
  27. }
  28. str += childrenArr.join(',');
  29. str += ']';
  30. }
  31. str += '}';
  32. }
  33. else {
  34. str = `"${parent}"`;
  35. }
  36. return str;
  37. }
  38. const table = {
  39. tagName: 'table',
  40. attrs: {
  41. border: "1",
  42. },
  43. children: [
  44. {
  45. tagName: 'tr',
  46. children: [
  47. {
  48. tagName: "td",
  49. children: ["1x1"],
  50. },
  51. {
  52. tagName: "td",
  53. children: ["1x2"],
  54. },
  55. ]
  56. },
  57. {
  58. tagName: 'tr',
  59. children: [
  60. {
  61. tagName: "td",
  62. children: ["2x1"],
  63. },
  64. {
  65. tagName: "td",
  66. children: ["2x2"],
  67. },
  68. ]
  69. }
  70. ]
  71. }
  72. var objStr = walker(table);;
  73. document.write(walker(objStr));
  74. </script>
  75. </body>