12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- <header>
- DOM Tree
- </header>
- <body>
- <script>
- function walker(parent) {
- let res = undefined;
- let tagName = parent.tagName;
- if (tagName) {
- res = document.createElement(tagName);
- let attrs = parent.attrs;
- if (attrs) {
- for (const attrName in attrs) {
- res[attrName] = attrs[attrName];
- }
- }
- for (const child of parent.children) {
- let childRes = walker(child)
- if (typeof childRes === "object") {
- res.append(childRes);
- }
- else {
- res.innerText = childRes;
- }
- }
- }
- else {
- res = parent;
- }
- return res;
- }
- 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"],
- },
- ]
- }
- ]
- }
- document.body.append(walker(table)); //вернет <table border='1' ....
- </script>
- </body>
|