JavaScript - createComment() method

revision:


Category : document

The createComment() method creates a new comment node, and returns it.

Syntax :

        document.createComment(data)
    

Parameters:

data : a string containing the data to be added to the Comment.

Examples:

            const docu = new DOMParser().parseFromString("<xml></xml>", "application/xml");
            const comment = docu.createComment(
            "This is a not-so-secret comment in your document"
            );
            docu.querySelector("xml").appendChild(comment);
            console.log(new XMLSerializer().serializeToString(docu));
            // Displays: <xml></xml>
        

Practical examples

example: create a comment

code:
                    <div>
                        <p id="comment"></p>
                        
                    </div>
                    <script>
                        const comment = document.createComment("My personal comments");
                        document.body.appendChild(comment);
                        document.getElementById("comment").innerHTML =
                        "A comment was added to this document, but as you know, comments are invisible.";
                    </script>