JavaScript Document createComment() Method

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline Widely available
Instance method

What You’ll Learn

document.createComment() is an instance method that creates a new comment node (see MDN Document: createComment()). Learn the data parameter, how comments appear as <!-- ... -->, inserting with append() or appendChild, and how comments differ from visible elements — with five try-it labs.

01

Kind

Instance method

02

Arg

data string

03

Returns

Comment

04

Visible?

No (UI)

05

Works in

HTML + XML

06

Status

Baseline

Introduction

HTML comments in markup look like this:

JavaScript
<!-- TODO: refactor this section -->

With JavaScript, document.createComment(data) builds the same kind of node in memory. MDN: it creates a new comment node and returns it.

💡
Comments are for developers, not users

Comment nodes do not appear on the rendered page. They show up in View Source, DevTools, and serialized HTML/XML. Use them for build notes or debugging — not for hiding secrets (comments are still readable).

Related tutorials: createCDATASection(), nodeType, append().

Understanding document.createComment()

An instance method on any Document object — including the live HTML page document (MDN).

  • Parameterdata: string for the comment text (MDN).
  • Return value — a new Comment object (MDN).
  • nodeTypeNode.COMMENT_NODE (8).
  • nodeName"#comment".
  • Content — read via nodeValue or textContent.
  • AttachappendChild, insertBefore, or append.

📝 Syntax

General form of Document.createComment (MDN):

JavaScript
createComment(data)

Parameters

  • data — string containing the comment text (MDN).

Return value

A new Comment object (MDN).

MDN XML example

JavaScript
const doc = new DOMParser().parseFromString("<xml></xml>", "application/xml");
const comment = doc.createComment(
  "This is a not-so-secret comment in your document"
);
doc.querySelector("xml").appendChild(comment);

console.log(new XMLSerializer().serializeToString(doc));
// <xml><!--This is a not-so-secret comment in your document--></xml>

HTML page example

JavaScript
const note = document.createComment("Loaded by script");
document.body.appendChild(note);
console.log(note.textContent); // "Loaded by script"

⚡ Quick Reference

GoalCode
Create commentdocument.createComment("note")
Insertparent.appendChild(comment)
Read textcomment.textContent
nodeTypeNode.COMMENT_NODE (8)
On new Documentdoc.createComment("note")
MDN statusBaseline Widely available

🔍 At a Glance

Four facts about document.createComment().

Returns
Comment

node

UI
hidden

not rendered

Type
8

COMMENT_NODE

Docs
HTML+XML

both

📋 Markup comment vs createComment()

ApproachWhenExample
HTML markupStatic template files<!-- note --> in .html
createComment()Dynamic scripts / buildersdoc.createComment("note")
DevToolsInspect attached commentsElements panel shows #comment
append() on DocumentRoot-level notes on in-memory docsdoc.append(doc.createComment("x"))

Examples Gallery

Examples follow MDN Document: createComment() and show HTML and XML usage.

📚 Getting Started

Create comments and serialize or read their text.

Example 1 — MDN: XML comment with DOMParser

Official MDN workflow for an XML document.

JavaScript
const doc = new DOMParser().parseFromString("<xml></xml>", "application/xml");
const comment = doc.createComment(
  "This is a not-so-secret comment in your document"
);
doc.querySelector("xml").appendChild(comment);

console.log(new XMLSerializer().serializeToString(doc));
Try It Yourself

How It Works

XMLSerializer wraps the comment text in <!-- ... -->.

Example 2 — Comment on the live HTML document

Unlike CDATA, comments work on the page’s HTML document.

JavaScript
const comment = document.createComment("Added by JavaScript");
document.getElementById("host").appendChild(comment);

console.log(comment.textContent);
// Page UI unchanged — check DevTools for #comment node
Try It Yourself

How It Works

The comment is in the DOM tree but does not render as visible content.

📈 Practical Patterns

Node inspection and insertion patterns.

Example 3 — nodeType is COMMENT_NODE (8)

Identify comment nodes in the tree.

JavaScript
const comment = document.createComment("debug marker");

console.log(comment.nodeType === Node.COMMENT_NODE); // true
console.log(comment.nodeName);  // "#comment"
console.log(comment.nodeValue); // "debug marker"
Try It Yourself

How It Works

Comments are a distinct node type, separate from elements and text nodes.

Example 4 — Insert before the first child

Place a comment at the top of a container with insertBefore.

JavaScript
const list = document.getElementById("list");
const marker = document.createComment("Start of list");

list.insertBefore(marker, list.firstChild);

console.log(list.firstChild.nodeName); // "#comment"
console.log(list.firstChild.textContent); // "Start of list"
Try It Yourself

How It Works

Comments participate in childNodes like any other node.

Example 5 — On a new Document() with append()

Same pattern as the append() tutorial.

JavaScript
const doc = new Document();
doc.append(doc.createComment("root note"));
doc.append(document.createElement("html"));

console.log(doc.childNodes.length); // 2
console.log(doc.firstChild.nodeName); // "#comment"
Try It Yourself

How It Works

In-memory documents can hold comment nodes alongside root elements.

🚀 Common Use Cases

  • Build-time markers — leave notes in programmatically generated HTML.
  • Template engines — insert comment nodes during DOM construction.
  • Debugging — mark sections in the tree (visible in DevTools).
  • XML pipelines — MDN XML example with XMLSerializer.
  • Not for secrets — comments are readable in source and DevTools.
  • Not for UI text — use createTextNode or elements instead.

🧠 How createComment() Works

1

Pass data string

MDN: text stored as the comment’s character data.

Input
2

Get detached Comment

Browser returns a node with nodeType 8.

Create
3

Append to a parent

appendChild, insertBefore, or append.

Attach
4

Serialized as <!-- data -->

Hidden from users; visible in source and DevTools.

📝 Notes

  • MDN: Baseline Widely available since July 2015.
  • Works on HTML and XML documents (unlike createCDATASection).
  • Comments do not render in the page UI.
  • Do not store sensitive data in comments.
  • nodeType is 8 (COMMENT_NODE).
  • Related: append(), nodeType, createCDATASection().

Browser Support

Document.createComment() is Baseline Widely available on MDN (since July 2015). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline Widely available

Document.createComment()

Creates Comment nodes — supported across all major browsers.

Baseline Widely available
Google Chrome Supported
Yes
Mozilla Firefox Supported
Yes
Apple Safari Supported
Yes
Microsoft Edge Supported
Yes
Opera Supported
Yes
Internet Explorer Supported (legacy)
Yes
createComment() Wide

Bottom line: Fully supported in HTML and XML documents. Use for developer notes, not visible UI content.

Conclusion

document.createComment(data) creates a Comment node for HTML or XML documents. Attach it with DOM insertion methods; it serializes as <!-- ... --> but never appears in the rendered page. For visible text, use elements or text nodes instead.

Continue with createDocumentFragment(), append(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Use for developer notes and build markers
  • Read content with textContent or nodeValue
  • Check nodeType === Node.COMMENT_NODE when filtering
  • Pair with append on in-memory Document objects
  • Use MDN’s XMLSerializer pattern for XML output

❌ Don’t

  • Store passwords or secrets in comments
  • Expect comments to show on the page
  • Use comments instead of proper UI elements
  • Assume users cannot read comment text
  • Confuse with createCDATASection (XML CDATA)

Key Takeaways

Knowledge Unlocked

Five things to remember about createComment()

Hidden comment nodes for developers.

5
Core concepts
👁02

UI

hidden

not shown
📄03

Type

8

COMMENT
🌐04

Works

HTML+XML

both
🛡05

Status

Baseline

2015

❓ Frequently Asked Questions

MDN: Document.createComment() creates a new comment node and returns it. The data string becomes the comment text inside <!-- ... --> when serialized.
No. MDN marks Document.createComment() as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard.
A new Comment object (MDN). Read comment.textContent or comment.nodeValue for the data string.
No. Comments do not render in the browser UI. They appear in HTML/XML source, DevTools, and serialized output — useful for notes to developers, not end users.
Yes. Unlike createCDATASection(), createComment() works on the live HTML document and on XML documents from DOMParser (MDN XML example).
Call parent.appendChild(comment) or parent.insertBefore(comment, refNode). The Comment node must be attached to appear in that parent’s subtree.
Did you know?

MDN’s XML example calls the comment “not-so-secret” on purpose — anything inside <!-- ... --> is still plain text in the document source. Never use comments to hide API keys or private data.

Next: createDocumentFragment()

Learn how to build offscreen DOM subtrees and insert them in one batch with DocumentFragment.

createDocumentFragment() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful