Computer >> 컴퓨터 >  >> 프로그램 작성 >> HTML

HTML DOM createComment() 메서드

<시간/>

HTML DOM createComment() 메소드는 주어진 텍스트로 주석 노드를 생성하는 데 사용됩니다. 생성할 주석을 매개변수로 사용합니다. 주석은 보이지 않으므로 이 메소드를 실행한 후 HTML 문서를 검사하여 작성된 주석을 확인해야 합니다.

구문

다음은 createComment() 메서드의 구문입니다. -

document.createComment( text );

여기에서 텍스트는 주석에 추가해야 하는 데이터가 포함된 문자열 유형입니다.

예시

createComment() 메서드의 예를 살펴보겠습니다.

<!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>

출력

이것은 다음과 같은 출력을 생성합니다 -

HTML DOM createComment() 메서드

주석을 클릭하고 코드를 검사한 후 HTML 문서에서 주석을 확인합니다. -

HTML DOM createComment() 메서드

위의 예에서 -

사용자가 클릭했을 때 Comment() 함수를 실행할 COMMENT 버튼을 만들었습니다.

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

Comment() 함수는 문서 객체의 createComment() 메서드를 사용하여 매개변수로 제공된 메시지로 주석을 생성합니다. 작성된 주석이 변수 x에 할당되었습니다.

그런 다음 document.body appendChild() 메서드를 사용하여 문서 본문에 주석을 추가합니다. 위에서 작성한 주석은 appendChild() 메소드에 매개변수로 전달됩니다. 적절한 메시지는 ID를 얻고 innerHTML 속성 값을 주어진 메시지로 설정하여

요소 내부에 표시됩니다. -

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";
}