คุณสมบัติ HTML DOM className ใช้สำหรับกำหนดคลาส CSS ให้กับองค์ประกอบ HTML คุณสมบัติ className ใช้สำหรับตั้งหรือคืนค่าค่าแอตทริบิวต์ class name ขององค์ประกอบ หากไม่มีคลาสเกี่ยวข้องกับองค์ประกอบ HTML แล้ว สตริงว่างจะถูกคืนค่า เราสามารถเปลี่ยนชื่อคลาสที่อยู่ภายในองค์ประกอบโดยใช้คุณสมบัตินี้ได้
ไวยากรณ์
ไวยากรณ์สำหรับ -
การตั้งค่าคุณสมบัติ className -
HTMLElementObject.className = class;
ที่นี่ ค่า class ใช้ระบุชื่อคลาสขององค์ประกอบ องค์ประกอบสามารถมีหลายคลาสเกี่ยวข้องกับมันแยกด้วยช่องว่าง
ตัวอย่าง
ลองดูตัวอย่างของคุณสมบัติ HTML DOM className -
<!DOCTYPE html> <html> <head> <style> .firstDiv { width: 300px; height: 100px; background-color:lightgreen; } .secondDiv{ color: red; border:solid 1px blue; margin-bottom:9px; } </style> </head> <body> <p>คลิกปุ่มด้านล่างเพื่อแสดงค่าแอตทริบิวต์ class ของ div</p> <div id="myDIV" class="firstDiv secondDiv"> This is a sample div element. </div> <button onclick="getClassName()">GET CLASS</button> <p id="Sample"></p> <script> function getClassName() { var x = document.getElementById("myDIV").className; document.getElementById("Sample").innerHTML = "The classNames with the div element are " + x; } </script> </body> </html>
ผลลัพธ์
จะได้ผลลัพธ์ดังนี้ -

เมื่อคลิกปุ่ม GET CLASS -

ในตัวอย่างข้างต้น -
เราสร้าง div ที่มี id "myDIV" และมีข้อความบางส่วนในมัน -
<div id="myDIV" class="firstDiv secondDiv"> This is a sample div element. </div>
เราสร้างปุ่ม GET CLASS ที่จะเรียกใช้เมธอด getClassName() เมื่อคลิก -
<button onclick="getClassName()">GET CLASS</button>
เมธอด getClassName() จะดึงองค์ประกอบ <div> โดยใช้เมธอด getElementById() และดึงชื่อคลาสทั้งหมดโดยใช้คุณสมบัติ className บนองค์ประกอบ <div> และกำหนดให้ตัวแปร x ชื่อคลาสจะถูกแสดงในย่อหน้าที่มี id "Sample" -
function getClassName() { var x = document.getElementById("myDIV").className; document.getElementById("Sample").innerHTML = "The classNames with the div element are " + x; }