JavaScript document createComment() Method Tutorial

In this section, we will learn what the document createComment() method is and how to use it in JavaScript.

What is document createComment() Method in JavaScript?

The document createComment() method is used to dynamically create a comment in an HTML source code using JavaScript.

You should know that creating comments using this method is independent from the document. That means we need to pick an element in a document and add this comment as its child or parent, etc. so that the comment appears in the source code at the right place.

This could be done using a method like appendChild().

Note: comments are invisible on a page and are only visible in the source code.

document createComment() Method Syntax:

document.createComment(comment);

document createComment() Method Parameters

The method takes one argument, and that is the comment we want to add to the source code of the document.

document createComment() Method Return Value

The return value of this method is a reference to a comment object that was created using this method.

Example: using document createComment() Method in JavaScript

See the Pen using document createComment() Method in JavaScript by Omid Dehghan (@odchan1) on CodePen.

How Does document createComment() Method Work?

In this example, we’ve created a new comment using the createComment() method and then used the appendChild() method to add this newly created comment to the <body> element as its last child.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies