index.js 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. /* Рекурсия: HTML tree
  2. Используя решение этого задания сделайте функцию, которая рекурсивно создает HTML-строку из древовидной структуры данных Javascript любой вложенности. Проверьте результат работы функции выводя HTML-строку используя document.write или же какой-то_элемент.innerHTML*/
  3. const table = {
  4. tagName: 'table',
  5. attrs: {
  6. border: "1",
  7. },
  8. children: [
  9. {
  10. tagName: 'tr',
  11. children: [
  12. {
  13. tagName: "td",
  14. children: ["1x1"],
  15. },
  16. {
  17. tagName: "td",
  18. children: ["1x2"],
  19. },
  20. ]
  21. },
  22. {
  23. tagName: 'tr',
  24. children: [
  25. {
  26. tagName: "td",
  27. children: ["2x1"],
  28. },
  29. {
  30. tagName: "td",
  31. children: ["2x2"],
  32. },
  33. ]
  34. }
  35. ]
  36. }
  37. //htmlTree(table) //вернет <table border='1' ....
  38. let result = ""
  39. function recursion (obj, str="") {
  40. console.log(obj.tagName)
  41. result += "<" + obj.tagName
  42. if (obj.attrs){
  43. for (property in obj.attrs) {
  44. result += ' ' + property + '="' + obj.attrs[property] + '"'
  45. }
  46. }
  47. result += ">"
  48. console.log(obj.children)
  49. let children
  50. if (obj.children){
  51. children = obj.children
  52. for (const obj of children){
  53. console.log(obj)
  54. if (typeof obj !== 'object') {
  55. result += obj
  56. }
  57. if(typeof obj === 'object') {
  58. recursion (obj, str)
  59. }
  60. }
  61. }
  62. result += "</" + obj.tagName + ">"
  63. }
  64. recursion(table)
  65. console.log(result)
  66. result =""
  67. const body = {
  68. tagName : 'body',
  69. children : [
  70. {
  71. tagName : 'div',
  72. children : [
  73. {
  74. tagName : 'span',
  75. children : ['Enter a data please:']
  76. },
  77. {
  78. tagName : 'br'
  79. },
  80. {
  81. tagName : 'input',
  82. attrs : {
  83. type : 'text',
  84. id : 'name'
  85. }
  86. },
  87. {
  88. tagName : 'input',
  89. attrs : {
  90. type : 'text',
  91. id : 'surname',
  92. }
  93. }
  94. ]
  95. },
  96. {
  97. tagName : 'div',
  98. children : [
  99. {
  100. tagName : 'button',
  101. attrs : {
  102. id : 'ok'
  103. },
  104. children : ['OK']
  105. },
  106. {
  107. tagName : 'button',
  108. attrs : {
  109. id : 'cancel'
  110. },
  111. children : 'Cancel'
  112. },
  113. ]
  114. }
  115. ]
  116. }
  117. recursion(body)
  118. console.log(result)