Open In App

HTML DOM createComment() Method

Last Updated : 02 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The createComment() method is used to create a comment node with some specified text. This property is used to set a text value as a parameter that is of string type. 

Syntax:

document.createComment( text )

Parameters: This method accepts single parameter text which is optional. This parameter is used to hold the comment string. 

Example: In this example, we will use createComment() method

html
<!DOCTYPE html>
<html>
  
<head>
    <title>DOM createComment() Method</title>
    <style>
        h1,
        h2 {
            color: green;
            font-weight: bold;
        }
    </style>
</head>

<body>
    <h1>GeeksForGeeks</h1>
    <h2>DOM createComment() Method</h2>
    <button onclick="geeks()">
      Submit
      </button>
    <p id="sudo"></p>
    <script>
        function geeks() {
            let c = document.createComment("GFG comments");
            document.body.appendChild(c);
            let x = document.getElementById("sudo");
            x.innerHTML = "Comments are Invisible!";
        }
    </script>
</body>
  
</html>

Output:

Supported Browsers: The browser supported by DOM createComment() Method properties are listed below:

You can insert a comment into a specific position using methods like insertBefore() or appendChild(). For example:

let comment = document.createComment('Inserted comment');
let referenceNode = document.getElementById('someElement');
referenceNode.parentNode.insertBefore(comment, referenceNode);

Is there a limit to the text length for comments created with createComment()?

There is no practical limit to the length of text in a comment created with createComment(), but very long comments may affect performance or readability in the source code.

Can comments created with createComment() contain HTML or JavaScript code?

Yes, comments can contain any text, including HTML or JavaScript code, but this text is not executed or rendered; it is just treated as a comment in the DOM.

How does createComment() differ from createTextNode()?

createComment() creates a comment node (<!– comment –>), whereas createTextNode() creates a text node that is visible on the page. They serve different purposes in the DOM.


Next Article
Article Tags :

Similar Reads