I am trying to turn the json data that is in the db variable into a nested list on the html page. Instead it is giving me a sort of ladder of each child node inserted into the child node before it. I can not figure out why it is not nesting correctly. What am i missing?
db = JSON.parse(`
{
"title": "Root",
"children": [
{
"title": "Child1",
"children": [
{"title": "Child1a"},
{"title": "Child1b"},
{"title": "Child1c"}
]
},
{
"title": "Child2",
"children": [
{"title": "Child2a"},
{"title": "Child2b"},
{"title": "Child2c"}
]
}
]
}
`);
function recurse(u, j) {
li = document.createElement('li');
ul = document.createElement('ul');
li.setAttribute('title', j.title);
li.appendChild(ul);
u.appendChild(li);
(j.children || []).forEach(c => {
recurse(ul, c);
});
}
recurse(document.getElementById('tree'), db);
* {
margin: 0;
}
li::before {
content: attr(title);
}
li:hover {
cursor: grab;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Scratch</title>
</head>
<body>
<ul id='tree'></ul>
</body>
</html>