12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- <header>
- HTML Tree
- </header>
- <body>
- <script>
- function walker(parent) {
- let str = "";
- let tagName = parent.tagName;
- if (tagName) {
- str = '{';
- str += `"tagName":"${tagName}",`;
- let attrs = parent.attrs;
- if (attrs) {
- str += '"attrs":{';
- let attrsArr = [];
- for (const attrName in attrs) {
- attrsArr.push(`"${attrName}":"${attrs[attrName]}"`);
- }
- str += attrsArr.join(',');
- str += '},';
- }
- if (parent.children) {
- str += '"children":['
- let childrenArr = [];
- for (const child of parent.children) {
- childrenArr.push(walker(child)); //вложенный вызов - вложенный уровень вложенности :-D
- }
- str += childrenArr.join(',');
- str += ']';
- }
- str += '}';
- }
- else {
- str = `"${parent}"`;
- }
- return str;
- }
- const table = {
- tagName: 'table',
- attrs: {
- border: "1",
- },
- children: [
- {
- tagName: 'tr',
- children: [
- {
- tagName: "td",
- children: ["1x1"],
- },
- {
- tagName: "td",
- children: ["1x2"],
- },
- ]
- },
- {
- tagName: 'tr',
- children: [
- {
- tagName: "td",
- children: ["2x1"],
- },
- {
- tagName: "td",
- children: ["2x2"],
- },
- ]
- }
- ]
- }
- var objStr = walker(table);;
- document.write(walker(objStr));
- </script>
- </body>
|