HTML - DOM Document createComment() 方法



createComment() 方法用於建立帶有指定文字的註釋節點。由於註釋不可見,因此必須在執行此方法後檢查 HTML 文件才能看到建立的註釋。

語法

document.createComment(text);

引數

此方法接受單個引數,如下所示。

引數 描述
text 表示您要新增到文件中的註釋。它是可選的。

返回值

它返回建立的註釋節點。

HTML DOM Document 'createComment()' 方法示例

這是一個使用 createComment() 方法向 HTML 文件添加註釋的示例。

<!DOCTYPE html>
<html lang="en">

<head>
   <title>
      HTML DOM document createComment() Method
   </title>
</head>

<body>
   <h3>HTML DOM document createComment() Method</h3>
   <button onclick="fun()">Click me</button>
   <p id="comment"></p>
   <script>
      function fun() {
         let x = document.createComment("This is a sample Comment");
         document.body.appendChild(x);
         let p = document.getElementById("comment");
         p.innerHTML = "The comment was added to this HTML document but is invisible";
      }
   </script>
</body>

</html>

支援的瀏覽器

方法 Chrome Edge Firefox Safari Opera
createComment() 是 1 是 12 是 1 是 1 是 12.1
html_dom_document_reference.htm
廣告