เมธอด 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> ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

หลังจากคลิกที่ COMMENT และตรวจสอบโค้ดเพื่อดูความคิดเห็นในเอกสาร HTML −

ในตัวอย่างข้างต้น −
เราได้สร้างปุ่ม 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";
}