แอตทริบิวต์ (Attributes) ใช้สำหรับกำหนดคุณสมบัติให้ element เช่น ความกว้าง/สูงของรูปภาพหรือ canvas ทุก element สามารถมี attribute ได้ และให้ข้อมูลเพิ่มเติม Attribute ประกอบด้วย ชื่อ (name) และ ค่า (value)
ตัวอย่าง
<canvas id="newCanvas" width="400" height="300">
<img alt="alternate text">
เครื่องหมายคำพูด: ตามมาตรฐาน HTML5 ไม่บังคับให้มี quotes รอบค่า attribute แต่ แนะนำให้ใส่เสมอ เพื่อป้องกันข้อผิดพลาดและอ่านง่าย
ตัวอย่างแอตทริบิวต์ต่างๆ
1. แอตทริบิวต์ start ของ <ol>
กำหนดค่าเริ่มต้นของรายการลำดับแรก
ไวยากรณ์: <ol start="num">
<!DOCTYPE html> <html> <body> <h1>ผลการสอบภาคปลาย MCA</h1> <h2>อันดับ 1-5</h2> <ol> <li>Steve</li> <li>David</li> <li>Kane</li> <li>William</li> <li>John</li> </ol> <h2>อันดับ 5-10</h2> <ol start="5"> <li>Tom</li> <li>Jack</li> <li>Will</li> <li>Harry</li> <li>Tim</li> </ol> </body> </html>
ผลลัพธ์: รายการแรกเริ่มที่ 1, รายการที่สองเริ่มที่ 5
2. แอตทริบิวต์ autofocus ของ <textarea>
ตั้งค่าให้ textarea ได้รับโฟกัสอัตโนมัติเมื่อโหลดหน้า (เพิ่มใน HTML5)
ไวยากรณ์: <textarea autofocus>
<!DOCTYPE html> <html> <body> <h2>คำถามสัมภาษณ์</h2> <p>ทำไมคุณจึงอยากเป็น Technical Writer? (100 คำ)</p> <textarea rows="6" cols="70" autofocus> เขียนคำตอบใน 100 คำ... </textarea> <p>จุดแข็งของคุณคืออะไร? (50 คำ)</p> <textarea rows="4" cols="70" autofocus> เขียนคำตอบใน 50 คำ... </textarea> </body> </html>
ผลลัพธ์: Textarea แรกจะได้รับโฟกัสเมื่อโหลดหน้า (textarea ที่สองก็มี autofocus แต่เบราว์เซอร์จะเลือกตัวแรก)
แอตทริบิวต์สำคัญอื่นๆ ที่ควรรู้จัก
| แอตทริบิวต์ | ใช้กับ | คำอธิบาย |
|---|---|---|
id | ทุก element | ตัวระบุเอกลักษณ์ (unique) |
class | ทุก element | กลุ่ม element (ซ้ำได้) |
style | ทุก element | Inline CSS |
title | ทุก element | Tooltip/คำอธิบายเพิ่มเติม |
hidden | ทุก element | ซ่อน element (boolean) |
data-* | ทุก element | Custom data attributes |
src | img, video, audio, iframe, script | แหล่งที่มาของไฟล์ |
alt | img, area, input | ข้อความทางเลือก (accessibility) |
href | a, link, area | URL ปลายทาง |
type | input, button, script, style | ประเภทของ element |
name | form elements | ชื่อสำหรับ form submission |
value | input, option, button, etc. | ค่าของ element |
placeholder | input, textarea | ข้อความแนะนำ |
required | form inputs | บังคับกรอก |
disabled | form elements | ปิดใช้งาน |
readonly | input, textarea | อ่านอย่างเดียว |
Global Attributes: id, class, style, title, hidden, data-*, tabindex, accesskey, contenteditable, dir, lang, spellcheck, translate — ใช้กับทุก element ได้