Metoda HTML DOM setAttributeNode()
❮ Obiekt elementuPrzykład
Ustaw węzeł atrybutu klasy elementu <h1>:
var h1 = document.getElementsByTagName("H1")[0]; // Get the first <h1> element in the document
var att = document.createAttribute("class"); // Create a "class" attribute
att.value = "democlass"; // Set the value of the class attribute
h1.setAttributeNode(att); // Add the class attribute to <h1>
Przed ustawieniem węzła atrybutu:
Hello World
Po ustawieniu węzła atrybutu:
Hello World
Więcej przykładów „Wypróbuj sam” poniżej.
Definicja i użycie
Metoda setAttributeNode() dodaje określony węzeł atrybutu do elementu.
Jeśli określony atrybut już istnieje, ta metoda go zastępuje.
Wartość zwracana przez tę metodę jest obiektem Attr. Aby uzyskać więcej informacji, zobacz Obiekt atrybutu HTML DOM .
Zobacz także metodę setAttribute() .
Wskazówka: Użyj metody removeAttributeNode() , aby usunąć węzeł atrybutu z elementu.
Obsługa przeglądarki
Method | |||||
---|---|---|---|---|---|
setAttributeNode() | Yes | Yes | Yes | Yes | Yes |
Składnia
element.setAttributeNode(attributenode)
Wartości parametrów
Parameter | Type | Description |
---|---|---|
attributenode | Attr object | Required. The attribute node you want to add |
Szczegóły techniczne
Wartość zwrotu: | Obiekt Attr, reprezentujący zastąpiony węzeł atrybutu, jeśli istnieje, w przeciwnym razie null |
---|---|
Wersja DOM | Obiekt elementu podstawowego poziomu 1 |
Więcej przykładów
Przykład
Ustaw węzeł atrybutu href elementu <a>:
var anchor = document.getElementById("myAnchor"); // Get the <a> element with id="myAnchor"
var att = document.createAttribute("href"); // Create a "href" attribute
att.value = "https://www.w3schools.com"; // Set the value of the href attribute
anchor.setAttributeNode(att); // Add the href attribute to <a>
Przed ustawieniem węzła atrybutu:
Go to w3schools.com
Po ustawieniu węzła atrybutu:
Powiązane strony
Samouczek HTML: atrybuty HTML
Dokumentacja HTML DOM: obiekt atrybutu HTML DOM
Dokumentacja HTML DOM: metoda setAttribute()
Dokumentacja HTML DOM: metoda document.createAttribute()
Dokumentacja HTML DOM: atrybut .value Property
Dokumentacja HTML DOM: metoda getAttributeNode()
Dokumentacja HTML DOM: metoda removeAttributeNode()
❮ Obiekt elementu