คุณสมบัติ attributes (attributes Property)
คุณสมบัติ attributes ที่เกี่ยวข้องกับแอตทริบิวต์ภายในแท็ก HTML คืนคอลเลกชันของแอตทริบิวต์ของโหนดที่กำหนด ในรูปแบบออบเจ็กต์ประเภท NamedNodeMap เข้าถึงโหนดเหล่านี้ได้ด้วยหมายเลข index (เริ่มจาก 0)
ไวยากรณ์ (Syntax)
node.attributes
ตัวอย่างการใช้งาน
ตัวอย่างด้านล่างแสดงการเข้าถึงแอตทริบิวต์ของอิลิเมนต์ <ol>
<!DOCTYPE html>
<html>
<body>
<p>Click the button the second attribute of the below list</p>
<button id="Btn" onclick="attributeFunc()">ATTR NAME</button>
<button id="Btn" onclick="attrLength()">ATTR LENGTH</button>
<ol id="LIST" type="A" start="5" reversed>
<li>ONE</li>
<li>TWO</li>
<li>THREE</li>
</ol>
<p id="SAMPLE"></p>
<script>
function attributeFunc() {
var x = document.getElementById("LIST").attributes[2].name;
document.getElementById("SAMPLE").innerHTML = x;
}
function attrLength() {
var x = document.getElementById("LIST").attributes.length;
document.getElementById("SAMPLE").innerHTML = x;
}
</script>
</body>
</html>
ผลลัพธ์
เริ่มต้น: ordered list พร้อมแอตทริบิวต์ id, type, start, reversed (4 attributes)
คลิก ATTR NAME: แสดงชื่อแอตทริบิวต์ index 2 คือ "start"
คลิก ATTR LENGTH: แสดงจำนวนแอตทริบิวต์ = 4
คำอธิบายโค้ด
- List element:
<ol id="LIST" type="A" start="5" reversed>มี 4 attributes - ฟังก์ชัน attributeFunc(): อ่าน
attributes[2].name→ "start" (index 0=id, 1=type, 2=start, 3=reversed) - ฟังก์ชัน attrLength(): อ่าน
attributes.length→ 4
คำอธิบายเพิ่มเติม
attributesเป็น NamedNodeMap - ไม่ใช่ array (ไม่มี forEach, map, filter)- ใช้
Array.from(node.attributes)หรือ[...node.attributes]แปลงเป็น array ได้ - แต่ละ item เป็น
Attrobject มีnameและvalue - ลำดับ attributes ไม่รับประกัน (implementation-dependent) แต่ใน browser ใหม่ๆ ตามลำดับใน markup
- วิธีเข้าถึงที่ดีกว่า:
element.getAttribute('name'),element.hasAttribute('name'),element.dataset(สำหรับ data-*)