ใน HTML DOM ทั้ง id และ class เป็น ตัวเลือกองค์ประกอบ (element selectors) ใช้ระบุตัวตนของ element จากชื่อที่กำหนด
ความแตกต่างสำคัญ
| # | หัวข้อ | id | class |
|---|---|---|---|
| 1 | ไวยากรณ์ (Syntax) | ใน HTML: id="uniqueName"ใน CSS: เริ่มด้วย # (เช่น #myId) |
ใน HTML: class="className"ใน CSS: เริ่มด้วย . (เช่น .myClass) |
| 2 | ตัวเลือก (Selector) | element เดียวมีได้ 1 id เท่านั้น | element เดียวมีได้ หลาย class (คั่นด้วยช่องว่าง) |
| 3 | ความเป็นเอกลักษณ์ (Uniqueness) | ไม่ซ้ำกันในหน้าเดียว — 1 id ต่อ 1 element | ซ้ำได้หลาย element — 1 class ใช้กับหลาย element |
ตัวอย่างเปรียบเทียบ
ตัวอย่าง id
<!DOCTYPE html>
<html>
<head>
<title>Id demo</title>
<style>
#idDemo {
color: green;
font-size: 25px;
}
</style>
</head>
<body style="text-align:center">
<h1>Get element by Id</h1>
<p id="idDemo">Demo for Id selector</p>
</body>
</html>
ตัวอย่าง class
<!DOCTYPE html>
<html>
<head>
<title>Class demo</title>
<style>
.classDemo {
color: orange;
font-size: 25px;
}
</style>
</head>
<body style="text-align:center">
<h1>Get element by class</h1>
<p class="classDemo">Demo for class selector</p>
</body>
</html>
การใช้งานใน JavaScript
document.getElementById("idName")— ดึง element เดียว (รวดเร็วที่สุด)document.getElementsByClassName("className")— ดึง HTMLCollection หลาย elementdocument.querySelector("#idName")/document.querySelector(".className")— เลือกตัวแรกที่เจอdocument.querySelectorAll(".className")— ดึง NodeList ทุกตัวที่ match
แนวทางปฏิบัติที่ดี (Best Practices)
- ใช้ id สำหรับ element ที่เป็นเอกลักษณ์: header, footer, main navigation, modal หลัก
- ใช้ class สำหรับกลุ่ม element ที่มีลักษณะร่วมกัน: buttons, cards, form inputs, grid items
- หลีกเลี่ยงการใช้ id ซ้ำ — จะทำให้ JavaScript และ CSS ทำงานผิดปกติ
- ชื่อ id/class ควรสื่อความหมาย (semantic) เช่น
.btn-primaryแทน.blue-button