Home / Content and Data / Threaded Comments

Threaded Comments in JavaScript, Free with Live Demo

Free threaded comment section in plain JavaScript. Nested replies, likes, edit and delete your own comments, sort by newest or top, collapse threads and friendly times like 2 hours ago.

Open live demoDownload HTML fileView code on GitHub
Threaded Comments JavaScript project: a comment section with nested replies, likes, editing, sorting and relative times

Runs on: Intl.RelativeTimeFormat and localStorage. Works in all modern browsers.

What is the Threaded Comments?

A comment section with nested replies, avatars, likes and friendly times. Write a comment, reply to anyone, and mentions like @Amira are highlighted.

Your own comments can be edited or deleted, threads can be collapsed, and you can sort by top, newest or oldest. Everything is saved in your browser.

Good for

  • Blog posts and articles
  • Product Q and A
  • Course lessons and community pages
  • Internal feedback tools

What this project does

How it works

  1. Comments are a treeEach comment has a list of replies, which have their own replies. One recursive function draws the whole tree, up to three levels deep.
  2. Friendly timesIntl.RelativeTimeFormat turns timestamps into 5 hours ago or yesterday, in the visitor's language.
  3. Keep threads readableDeleting a comment with replies leaves a placeholder so the conversation still makes sense. Long threads can be collapsed.

The key JavaScript

This is the heart of the project. The full file has the rest, including the screen layout and error handling.

function render(comments, depth = 1) {
  return "<ul>" + comments.map((c) => `
    <li><b>${c.who}</b> <time>${ago(c.time)}</time>
      <p>${escape(c.text)}</p>
      ${depth < 3 ? `<button data-reply="${c.id}">Reply</button>` : ""}
      ${c.replies.length ? render(c.replies, depth + 1) : ""}
    </li>`).join("") + "</ul>";
}
const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
rtf.format(-1, "day"); // "yesterday"

How to use it

  1. Click Download HTML file above.
  2. Open the file in a code editor, like VS Code.
  3. Run it from a local server with npx serve . so the camera, microphone and AI features are allowed.
  4. Change the text and colors, then upload it to GitHub Pages, Netlify or your own site. It is one file with no build step.

Questions people ask

How do I save comments for everyone?

Send new comments to your server with fetch and load the tree from there. The demo keeps them in localStorage only.

Is user text safe to show?

Yes. Text is escaped before display, so nobody can inject HTML or scripts.

Why limit nesting to three levels?

Deep threads get too narrow to read on phones. Three levels keeps conversations clear.

More Content and Data projects