เมธอด HTML DOM createAttribute() ใช้สำหรับสร้างแอตทริบิวต์เฉพาะโดยใช้ JavaScript สำหรับองค์ประกอบ HTML เมธอด createAttribute() จะสร้างแอตทริบิวต์ด้วยชื่อที่กำหนดและส่งกลับแอตทริบิวต์เป็นวัตถุ Attr
ไวยากรณ์
ต่อไปนี้เป็นไวยากรณ์สำหรับ createAttribute() วิธีการ -
document.createAttribute(attributename)
ตัวอย่าง
ให้เราดูตัวอย่างสำหรับ HTML DOM createAttribute() วิธีการ -
<!DOCTYPE html>
<html>
<head>
<title>CREATE ATTRIBUTE</title>
<style>
#DIV1{
margin-top:15px;
width:250px;
height:200px;
border:2px solid blue;
background-color:lightgreen;
}
</style>
</head>
<body>
<p>Click the button to create a "class" attribute for the div element</p>
<button onclick="attrCreate()">CREATE</button>
<br>
<div>
<p>This is a sample div</p>
</div>
<script>
function attrCreate() {
var x = document.getElementsByTagName("div")[0];
var att = document.createAttribute("id");
att.value = "DIV1";
x.setAttributeNode(att);
}
</script>
</body>
</html> ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

เมื่อคลิกปุ่มสร้าง -

ในตัวอย่างข้างต้น −
เราได้สร้างสไตล์ด้วยรหัส “DIV1”
#DIV1{
margin-top:15px;
width:250px;
height:200px;
border:2px solid blue;
background-color:lightgreen;
} เราได้สร้าง
องค์ประกอบที่มี
องค์ประกอบอยู่ภายใน
<div> <p>This is a sample div</p> </div>
จากนั้น เราได้สร้างปุ่ม CREATE ซึ่งจะรันฟังก์ชัน attrCreate() เมื่อผู้ใช้คลิก -
<button onclick="attrCreate()">CREATE</button>
ฟังก์ชัน attrCreate() รับองค์ประกอบ
โดยใช้เมธอด getElementsByTagName() บนออบเจ็กต์เอกสารและกำหนดให้กับตัวแปร x เมื่อใช้เมธอด createAttribute() เราสร้างแอตทริบิวต์ "id" และใช้คุณสมบัติ value ของมันเพื่อกำหนดค่า "DIV1" ซึ่งเป็น id ของสไตล์ที่เราสร้างไว้ก่อนหน้านี้ สุดท้าย เราตั้งค่าแอตทริบิวต์ "id" พร้อมกับค่าเป็นองค์ประกอบ
-
function attrCreate() {
var x = document.getElementsByTagName("div")[0];
var att = document.createAttribute("id");
att.value = "DIV1";
x.setAttributeNode(att);
}