เมธอด HTML DOM console.group() ใช้ระบุจุดเริ่มต้นของกลุ่มข้อความ และข้อความทั้งหมดที่เขียนหลังจากเมธอดนี้จะถูกเขียนภายในกลุ่มข้อความ อนุญาตให้ทำกลุ่มเดียวสำหรับข้อความทั้งหมด หรือหลายกลุ่มโดยใช้พารามิเตอร์ label
ไวยากรณ์
ไวยากรณ์สำหรับเมธอด console.group() ดังนี้ -
console.group([label])
ที่นี่ label เป็นพารามิเตอร์ทางเลือก เป็นประเภท string และทำหน้าที่เป็นป้ายกำกับสำหรับกลุ่มข้อความที่สร้าง
ตัวอย่าง
ลองดูตัวอย่างสำหรับเมธอด HTML DOM console.group() -
<!DOCTYPE html> <html> <body> <h1>console.group() Method</h1> <p>กด F12 เพื่อดูข้อความในมุมมองคอนโซล</p> <button type="button" onclick="normMessage()">NORMAL</button> <button type="button" onclick="groupMessage()">GROUP</button> <script> function normMessage(){ console.log("Hello world!"); } function groupMessage(){ console.group(); console.log("This message will be inside a group!"); console.log("This message will also be inside a group!"); } </script> </body> </html>
ผลลัพธ์
จะได้ผลลัพธ์ดังนี้ -

เมื่อคลิกปุ่ม NORMAL และดูคอนโซล -

เมื่อคลิกปุ่ม GROUP และดูคอนโซล -

ในตัวอย่างข้างต้น -
เราสร้างปุ่มสองปุ่ม NORMAL และ GROUP ที่จะเรียกใช้เมธอด normMessage() และ groupMessage() เมื่อถูกคลิกโดยผู้ใช้ -
<button type="button" onclick="normMessage()">NORMAL</button> <button type="button" onclick="groupMessage()">GROUP</button>
เมธอด normMessage() มีเมธอด console.log() ที่รับสตริงหรืออ็อบเจกต์ที่จัดส่งเป็นพารามิเตอร์และเพียงแค่แสดงบนคอนโซล -
function normMessage(){ console.log("Hello world!"); }
เมธอด groupMessage() มีเมธอด console.group() ภายในที่ระบุว่าข้อความทั้งหมดที่เขียนหลังจุดนี้จะแสดงภายในกลุ่มข้อความ -
function groupMessage(){ console.group(); console.log("This message will be inside a group!"); console.log("This message will also be inside a group!"); }