I have multiple path strings (One for each leaf node) such as
item1
item2
Folder with some children / Sub-item 3.1
Folder with some children / Sub-item 3.2
Document with some children / Sub-item 4.1
Document with some children / Sub-item 4.2
Where item 1,item 2, Sub-item 3.1,3.2,4.1, and 4.2 are leaf nodes; And what I want to do is build a nested HTML like this:
<ul>
<li>item1
<li>item2
<li>Folder with some children
<ul>
<li>Sub-item 3.1
<li>Sub-item 3.2
</ul>
<li>Document with some children
<ul>
<li>Sub-item 4.1
<li>Sub-item 4.2
</ul>
</ul>
Or a JSON object like this:
[
{title: "Item 1"},
{title: "Item 2"},
{title: "Folder with some children",
children: [
{title: "Sub-item 3.1"},
{title: "Sub-item 3.2"}
]
},
{title: "Document with some children",
children: [
{title: "Sub-item 4.1"},
{title: "Sub-item 4.2"}
]
}
]
But I’m having a hard time doing this. I’ve spent 10 hours on this to no avail. I’m open to using jquery. Please can you guide me in the right direction? My javascript is still not good enough to do these things on the fly.
I found that the best way to do this was to build the html elements using javascript’s createElement and a recursive function and just append it to the DOM in the end.