เอกสาร HTML DOM createAttribute()
ตัวอย่าง
// Create a class attribute:
const att = document.createAttribute("class");
// Set the value of the class attribute:
att.value = "democlass";
// Add the class attribute to the first h1:
const h1 = document.getElementsByTagName("H1")[0];
h1.setAttributeNode(att);
// Create a style attribute:
const att = document.createAttribute("style");
// Set the value of the style attribute:
att.value = "color:red";
// Add the style attribute to the first h1:
const h1 = document.getElementsByTagName("h1")[0];
h1.setAttributeNode(att);
ตัวอย่างเพิ่มเติมด้านล่าง
ความหมายและการใช้งาน
วิธี การcreateAttribute()
สร้างแอตทริบิวต์และส่งกลับแอตทริบิวต์เป็นวัตถุ Attr
ทางเลือก:
ง่ายกว่าที่จะใช้องค์ประกอบ .setAttribute()วิธีการ
ดูสิ่งนี้ด้วย:
ไวยากรณ์
document.createAttribute(name)
พารามิเตอร์
Parameter | Description |
name | Required. The name of the attribute to create. |
คืนมูลค่า
พิมพ์ | คำอธิบาย |
โหนด | โหนดแอตทริบิวต์ที่สร้างขึ้น |
ตัวอย่างเพิ่มเติม
เพิ่มแอตทริบิวต์ href="www.w3schools.com" ให้กับองค์ประกอบสมอ:
// Create a href attribute:
const att = document.createAttribute("href");
// Set the value of the href attribute:
att.value = "https://www.w3schools.com";
// Add the href attribute to an element:
element.setAttributeNode(att);
รองรับเบราว์เซอร์
document.createAttribute()
เป็นคุณลักษณะ DOM ระดับ 1 (1998)
ได้รับการสนับสนุนอย่างเต็มที่ในเบราว์เซอร์ทั้งหมด:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |