I've got this code and I need to transform ti to DOM structure (more information below)
const data = [
{
"type": "paragraph",
"children": [
{
"type": "text",
"text": "Hey all!"
},
{
"type": "break"
},
{
"type": "break"
},
{
"type": "text",
"text": " It's been a while since we partied "
},
{
"type": "important",
"children": [
{
"type": "text",
"text": "together"
}
]
},
{
"type": "text",
"text": " in a pool full of people!"
}
]
},
{
"type": "heading",
"id": "table-of-contents",
"level" : 2,
"children": [
{
"type": "text",
"text": "Table of contents:"
}
]
},
{
"type": "list",
"bullet": "decimal",
"children": [
{
"type": "listitem",
"children": [
{
"type": "anchor",
"href": "#table-of-contents",
"children": [
{
"type": "text",
"text": "How to start a podcast?"
},
{
"type": "text",
"text": ""
}
]
},
{
"type": "text",
"text": "Where to find your topics?"
}
]
},
{
"type": "listitem",
"children": [
{
"type": "text",
"text": "Where to find your topics?"
}
]
},
{
"type": "listitem",
"children": [
{
"type": "text",
"text": "What equipment do you need?"
}
]
}
]
}
]
What is the best way to do it?
I mean, should I do
const wrapper = document.createElement("div");
data.forEach(element => {
if(element.type === "paragraph") {
const paragraph = document.createElement("p");
element.children.forEach(kiddo => {
if(kiddo.type === "text") {
const textNode = document.createTextNode(kiddo.text);
paragraph.appendChild(textNode);
}
});
}
})
..and so on? I mean do I have to use "createElement/createTextNode" functions or does javascript have some kind of DOMBuilder than I can convert such structure into DOM?
types) as methods, iterate the data recursively, and call a suitable type method fromtypesobject on every type. You've also to keep book of the parent element to append the newly-created HTML element.