HTML DOM createComment() method


The HTML DOM createComment() method is used for creating a comment node with the given text. It takes the comment to be created as a parameter. Since comments are not visible you have to inspect the HTML document after executing this method to see the comment created.

Syntax

Following is the syntax for the createComment() method −

document.createComment( text );

Here, text is of type string containing the data that has to be added to the comment.

Example

Let us look at an example for the createComment() method −

<!DOCTYPE html>
<html>
<body>
<p>Click on below button to create and add a comment to this HTML document.</p>
<button onclick="Comment()">COMMENT</button>
<p id="Sample"></p>
<script>
   function Comment() {
      var x = document.createComment("This is a sample comment");
      document.body.appendChild(x);
      var p = document.getElementById("Sample");
      x.innerHTML = "The comment was added and can only be seen in the HTML document only";
   }
</script>
<p>Inspect the code to see the comment in the html document</p>
</body>
</html>

Output

This will produce the following output −

After clicking on the COMMENT and inspecting the code to see the comment in the HTML document. −

In the above example −

We have created a button COMMENT that will execute the Comment() function when clicked by the user.

<button onclick="Comment()">COMMENT</button>

The Comment() function uses the createComment() method of the document object to create a comment with the message that was supplied as parameter to it. The comment created was assigned to variable x.

The comment is then added to the document body using the document.body appendChild() method. The comment created above is passed as a parameter to appendChild() method. A suitable message is then dispayed inside the <p> element by getting its id and setting its innerHTML property value to the given message −

function Comment() {
   var x = document.createComment("This is a sample comment");
   document.body.appendChild(x);
   var p = document.getElementById("Sample");
   x.innerHTML = "The comment was added and can only be seen in the HTML document only";
}
raja
Published on 08-Aug-2019 16:38:34
Advertisements