Skip to content

Instantly share code, notes, and snippets.

@evdokimovm
Created April 2, 2023 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evdokimovm/4606d2e29dd299a52f3160b0ab8369d9 to your computer and use it in GitHub Desktop.
Save evdokimovm/4606d2e29dd299a52f3160b0ab8369d9 to your computer and use it in GitHub Desktop.
tree comments structure simple client side example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
var comments = [
{
id: 1,
text: "This is a top-level comment",
replies: [
{
id: 2,
text: "This is a reply to comment 1",
replies: [
{
id: 4,
text: "This is a reply to comment 2",
replies: []
}
]
},
{
id: 3,
text: "This is another reply to comment 1",
replies: []
}
]
},
{
id: 5,
text: "This is another top-level comment",
replies: []
}
]
function buildCommentTree(comments, container) {
comments.forEach(comment => {
var commentEl = document.createElement("div")
commentEl.classList.add("comment")
commentEl.innerHTML = comment.text
container.appendChild(commentEl)
if (comment.replies.length > 0) {
var repliesEl = document.createElement("div")
repliesEl.classList.add("replies")
container.appendChild(repliesEl)
buildCommentTree(comment.replies, repliesEl)
}
})
}
</script>
<div id="comments-container"></div>
<script>
var container = document.querySelector("#comments-container")
buildCommentTree(comments, container)
</script>
<style>
.comment {
margin: 10px;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
.replies {
margin-left: 20px;
}
</style>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment