HTML DOM Document createAttribute()
Przykłady
// 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);
Więcej przykładów poniżej.
Definicja i użycie
Metoda createAttribute()
tworzy atrybut i zwraca go jako obiekt Attr.
Alternatywny:
Łatwiej jest skorzystać z metody element .setAttribute() .
Zobacz też:
Składnia
document.createAttribute(name)
Parametry
Parameter | Description |
name | Required. The name of the attribute to create. |
Wartość zwrotu
Rodzaj | Opis |
Węzeł | Utworzony węzeł atrybutu. |
Więcej przykładów
Dodaj atrybut a href="www.w3schools.com" do elementu kotwicy:
// 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);
Obsługa przeglądarki
document.createAttribute()
jest funkcją DOM Level 1 (1998).
Jest w pełni obsługiwany we wszystkich przeglądarkach:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |