คุณสมบัติ HTML DOM className ใช้เพื่อกำหนดคลาส css ให้กับองค์ประกอบ HTML คุณสมบัติ className ใช้สำหรับการตั้งค่าหรือส่งคืนค่าแอตทริบิวต์ชื่อคลาสขององค์ประกอบ หากไม่มีคลาสที่เชื่อมโยงกับองค์ประกอบ HTML สตริงว่างจะถูกส่งคืน เราสามารถเปลี่ยนชื่อคลาสที่มีองค์ประกอบโดยใช้คุณสมบัตินี้ -
ไวยากรณ์
ต่อไปนี้เป็นไวยากรณ์สำหรับ −
การตั้งค่าคุณสมบัติ className -
HTMLElementObject.className = 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>Click the below button to display the class attribute value of the 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() จะได้รับองค์ประกอบ
function getClassName() {
var x = document.getElementById("myDIV").className;
document.getElementById("Sample").innerHTML ="The classNames with the div element are "+x;
}