HTML DOM Document createAttribute ()
Các ví dụ
// 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);
Thêm ví dụ bên dưới.
Định nghĩa và Cách sử dụng
Phương createAttribute()
thức tạo một thuộc tính và trả về thuộc tính dưới dạng một đối tượng Attr.
Thay thế:
Sẽ dễ dàng hơn khi sử dụng phương thức .setAttribute () của phần tử .
Xem thêm:
Cú pháp
document.createAttribute(name)
Thông số
Parameter | Description |
name | Required. The name of the attribute to create. |
Giá trị trả lại
Loại | Sự miêu tả |
Nút | Nút thuộc tính đã tạo. |
Các ví dụ khác
Thêm thuộc tính href = "www.w3schools.com" vào một phần tử liên kết:
// 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);
Hỗ trợ trình duyệt
document.createAttribute()
là một tính năng DOM Level 1 (1998).
Nó được hỗ trợ đầy đủ trong tất cả các trình duyệt:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |