Attribute
class มักถูกใช้เพื่อ
เชื่อมโยงกับชื่อ Class ใน Style Sheet (CSS)
ใช้โดย JavaScript เพื่อเข้าถึงและจัดการองค์ประกอบ (Elements) ที่มีชื่อ Class นั้น การใช้ Class Attribute
Attribute class มักถูกใช้เพื่ออ้างอิงชื่อคลาสที่กำหนดไว้ใน Style Sheet (CSS) นอกจากนี้ยังสามารถใช้ร่วมกับ JavaScript เพื่อเข้าถึงและจัดการองค์ประกอบ (Elements) ที่มีชื่อคลาสนั้นได้
ตัวอย่างด้านล่างแสดงการใช้
<div> ทั้ง 3 ตัว โดยมี class="city" ซึ่งถูกจัดรูปแบบด้วย CSS ชื่อ .city
London
London is the capital of England.
Paris
Paris is the capital of France.
Tokyo
Tokyo is the capital of Japan.
ตัวอย่างนี้ใช้
<span> สองตัว โดยมี class="note" เพื่อกำหนดรูปแบบข้อความให้เหมือนกัน
นี่คือ ข้อความสำคัญ ส่วนหัวเรื่อง
นี่เป็นเพียงบางส่วน ข้อความสำคัญ ของบทความ
⚠️ หมายเหตุ
Attribute class สามารถใช้ได้กับ Element HTML ทุกชนิด ระวังเรื่องตัวพิมพ์เล็ก–ใหญ่ของชื่อ Class ด้วย!
Syntax ของ Class
การสร้าง Class ใน CSS ใช้เครื่องหมายจุด (
.) นำหน้าชื่อ Class
แล้วกำหนด CSS Properties ภายใน { }
The class Attribute
การใช้ CSS กับ style Elements โดยใช้ชื่อ class ว่า "city":
London
London is the capital of England.
Paris
Paris is the capital of France.
Tokyo
Tokyo is the capital of Japan.
Multiple Classes
Element หนึ่งสามารถมีได้ มากกว่าหนึ่ง Class
โดยคั่นชื่อคลาสแต่ละอันด้วย ช่องว่าง
เช่น
ตัวอย่างนี้
<h2> ตัวแรกมีทั้ง Class city และ main
London
Paris
Tokyo
Elements ต่างกัน ใช้ Class เดียวกันได้
แม้ว่า Element จะต่างชนิดกัน ก็สามารถใช้ Class เดียวกันเพื่อแชร์รูปแบบเดียวกันได้
Paris
Paris is the capital of France
การใช้ Class กับ JavaScript
JavaScript สามารถเข้าถึงและจัดการ Elements ด้วยชื่อ Class โดยใช้ document.getElementsByClassName()
สรุป
classใช้ระบุชื่อให้กับ Elements อย่างน้อย 1 ชื่อ- CSS และ JavaScript ใช้ชื่อ Class เพื่อเลือกและเข้าถึง Elements ได้
classใช้ได้กับทุก Element HTML- ระวังตัวพิมพ์เล็ก–ใหญ่ของชื่อ Class
- Elements ต่างชนิดกันสามารถใช้ Class เดียวกันได้
- JavaScript เข้าถึง Elements ด้วย
getElementsByClassName()