I have the following data
const data = {
name: "Root",
children: [
{
name: "Folder 1",
children: [
{
name: "Folder 1-1",
},
{
name: "Folder 1-2",
},
],
},
{
name: "Folder 2",
children: [
{
name: "Folder 2-1",
},
{
name: "Folder 2-2",
},
],
},
],
};
how do i just use javascript to generate html tags like below. Please help me, thank you all!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tree folder</title>
<link rel="stylesheet" href="../main.css">
</head>
<style>
.children-list {
padding-left: 12px;
}
</style>
<body>
<div class="static-page">
<div class="container">
<div class="tree">
<div class="flex items-center gap-x-12 font-bold">
<span>-</span>
<span>Root</span>
</div>
<div class="children-list">
<div class="children-item">
<div class="flex items-center gap-x-12 font-bold">
<span>-</span>
<span>Folder 1</span>
</div>
<div class="children-list">
<div>
<div class="flex items-center gap-x-12 font-bold">
<span>-</span>
<span>Folder 1 - 1</span>
</div>
</div>
<div>
<div class="flex items-center gap-x-12 font-bold">
<span>-</span>
<span>Folder 1 - 2</span>
</div>
</div>
</div>
</div>
<div class="children-item">
<div class="flex items-center gap-x-12 font-bold">
<span>-</span>
<span>Folder 2</span>
</div>
<div class="children-list">
<div>
<div class="flex items-center gap-x-12 font-bold">
<span>-</span>
<span>Folder 2 - 1</span>
</div>
</div>
<div>
<div class="flex items-center gap-x-12 font-bold">
<span>-</span>
<span>Folder 2 - 2</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
<script src="./index.js"></script>
</html>
2
Answers
By using
for loop
. Like:Something like this – a recursive function that walks your data and creates elements and puts them where they belong: