123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
- <body>
- <script>
- var someTree = {
- tagName: "table", //html tag
- subTags: [ //вложенные тэги
- {
- tagName: "tr",
- subTags: [
- {
- tagName: "td",
- text: "some text",
- },
- {
- tagName: "td",
- text: "some text 2",
- }
- ]
- }
- ],
- attrs:
- {
- border: 1,
- },
- }
- var element = ""
- function toHtmlStr(obj) {
- if (obj.tagName !== undefined){
- element+= "<" + obj.tagName
- if (obj.attrs !== undefined) {
- let attrs = obj.attrs
- for (let key in attrs) {
- element += ` ${key}=${attrs[key]}` + ">\n"
- }
- } else {
- element += ">\n"
- }
- if (obj.text !== undefined) {
- element += `${obj.text}`
- }
- if (obj.subTags !== undefined) {
- let children = obj.subTags
- for (let i = 0; i < children.length; i++) {
- let childrenObj = children[i]
- toHtmlStr(childrenObj)
-
- }
- element+= `</${obj.tagName}>\n`
- } else {
- element+= `</${obj.tagName}>\n`
- }
- }
- return element
- }
- toHtmlStr(someTree)
- document.write(element)
- function toHtml(obj) {
- var element = document.createElement(obj.tagName);
-
- if (obj.text !== undefined) {
- element.innerHTML = obj.text
- }
- if (undefined !== obj.attrs) {
- for (let key in obj.attrs) {
- element[key] = obj.attrs[key]
- }
- }
-
- if (obj.subTags !== undefined) {
- for (let i = 0; i < obj.subTags.length; i++) {
- element.appendChild(toHtml(obj.subTags[i]));
- }
- }
- return element;
- }
- // document.body.appendChild(toHtml(someTree));
- </script>
- </body>
- </html>
|