Example 1 — Create Comment and Serialize XML
Parse a tiny XML document, append a comment, then serialize it (MDN-style).
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> How It Works
- Parse XML.
application/xmlbuilds a real XML document. - Create comment.
createComment(data)returns a detachedComment. - Append. The node must be attached before serialization shows it.
- Serialize.
XMLSerializerprints the classic<!--…-->wrapper.

