ใช้เมธอด HTML DOM console.clear() เพื่อล้างคอนโซล เมธอด console.clear() จะเขียนข้อความ "Console was cleared" ในคอนโซลและล้างเนื้อหาคอนโซลก่อนหน้าทั้งหมด เบราว์เซอร์ทั้งหมดรองรับวิธีนี้อย่างสมบูรณ์
ไวยากรณ์
ต่อไปนี้เป็นไวยากรณ์สำหรับวิธี console.clear() -
console.clear()
ตัวอย่าง
ให้เราดูตัวอย่างสำหรับ HTML DOM console.clear() วิธีการ -
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript console.clear() Method</h1>
<p>Press F12 on the keyboard to see the message on your console</p>
console.log("TEXT has been printed on the console!");
<p>Click the below button to clear the console</p>
<button onclick="clearConsole()">CLEAR</button>
<script>
function clearConsole() {
console.clear();
}
</script>
</body>
</html> ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

คอนโซล −

เมื่อคลิกปุ่ม CLEAR -

ในตัวอย่างข้างต้น −
เราได้เขียนข้อความไปยังคอนโซลโดยใช้เมธอด console.log() -
console.log("TEXT has been printed on the console!"); เราได้สร้างปุ่ม CLEAR ที่จะรันเมธอด clearConsole() -
<button onclick="clearConsole()">CLEAR</button>
clearConsole() วิธีการเรียกใช้ฟังก์ชัน clear() บนวัตถุคอนโซล การดำเนินการนี้จะล้างคอนโซลและเขียนว่า "คอนโซลถูกล้าง" บนคอนโซล
function clearConsole() {
console.clear();
}