var someTree = {
tagName: "table", //html tag
subTags: [ //вложенные тэги
{
tagName: "tr",
subTags: [
{
tagName: "td",
text: "some text",
},
{
tagName: "td",
text: "some text 2",
}
]
}
],
attrs:
{
border: 1,
},
}
<table border=1>
<tr>
<td>some text</td>
<td>some text 2</td>
</tr>
</table>
const body = {
tagName: "body",
subTags: [
{
tagName: "div",
subTags: [
{
tagName: "span",
text: "Enter a data please:",
},
{
tagName: "br",
},
{
tagName: "input",
attrs: {
type: "text",
id: "name",
},
},
{
tagName: "input",
attrs: {
type: "text",
id: "surname",
},
},
],
},
{
tagName: "div",
subTags: [
{
tagName: "button",
attrs: {
id: "ok",
},
text: "OK",
},
{
tagName: "button",
attrs: {
id: "cancel",
},
text: "Cancel",
},
],
},
],
};
const voidTags = [ 'input', 'img', 'br', 'hr', ещё какой-то тэг, и ещё, ... ];
function createHTML(data) {
const attrs = Object
.entries(data.attrs ?? {})
.map(n => `${n[0]}="${n[1]}"`)
.join(' ');
const startTag = `<${data.tagName}${attrs && (' ' + attrs)}>`;
if (voidTags.includes(data.tagName)) {
return startTag;
}
const children = (data.subTags ?? [])
.map(createHTML)
.join('');
return `${startTag}${data.text ?? ''}${children}</${data.tagName}>`;
}