html_tree.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. let someTree = {
  2. tagName: "table", //html tag
  3. children: [ //вложенные тэги
  4. {
  5. tagName: "tr",
  6. children: [
  7. {
  8. tagName: "td",
  9. text: "some text 11",
  10. children: [
  11. {
  12. tagName: "span",
  13. text: "some text 222",
  14. }
  15. ]
  16. },
  17. {
  18. tagName: "td",
  19. text: "some text 33",
  20. }
  21. ]
  22. },
  23. {
  24. tagName: "tr",
  25. children: [
  26. {
  27. tagName: "td",
  28. text: "some text 44",
  29. children: [
  30. {
  31. tagName: "span",
  32. text: "some text 555",
  33. }
  34. ]
  35. },
  36. {
  37. tagName: "td",
  38. text: "some text 66",
  39. }
  40. ]
  41. }
  42. ],
  43. attrs:
  44. {
  45. border: 1,
  46. },
  47. }
  48. let resultStr = '';
  49. const objectWalker = (object) => {
  50. for (const attr in object.attrs) {
  51. resultStr += `<${object.tagName} ${attr}="${object.attrs[attr]}">`;
  52. }
  53. if(object.children) {
  54. for (let child of object.children) {
  55. resultStr += `<${child.tagName}>${child.text ? child.text : ''}`;
  56. objectWalker(child);
  57. }
  58. }
  59. return resultStr += `</${object.tagName}>`;
  60. }
  61. console.log(objectWalker(someTree)); // <table border="1"><tr><td>some text 11<span>some text 222</span></td><td>some text 33</td></tr><tr><td>some text 44<span>some text 555</span></td><td>some text 66</td></tr></table>