เมธอด HTML DOM console.group() ใช้เพื่อระบุการเริ่มต้นของกลุ่มข้อความ และข้อความทั้งหมดที่เขียนหลังจากเมธอดนี้จะถูกเขียนภายในกลุ่มข้อความ ซึ่งช่วยให้สร้างกลุ่มเดียวสำหรับข้อความทั้งหมดหรือหลายกลุ่มโดยใช้พารามิเตอร์ป้ายกำกับ
ไวยากรณ์
ต่อไปนี้เป็นไวยากรณ์สำหรับเมธอด console.group() -
console.group([label])
ในที่นี้ เลเบลเป็นพารามิเตอร์ที่ไม่บังคับ เป็นประเภทสตริงและทำหน้าที่เป็นป้ายกำกับสำหรับกลุ่มข้อความที่สร้างขึ้น
ตัวอย่าง
ให้เราดูตัวอย่างสำหรับ HTML DOM console.group() วิธีการ -
<!DOCTYPE html>
<html>
<body>
<h1>console.group() Method</h1>
<p>Press F12 key to view the message in the console view.</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!");
}