Metodo HTML DOM setAttributeNode()
❮ L'oggetto elementoEsempio
Imposta il nodo dell'attributo di classe di un elemento <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>
Prima di impostare il nodo attributo:
Hello World
Dopo aver impostato il nodo attributo:
Hello World
Altri esempi "Provalo da solo" di seguito.
Definizione e utilizzo
Il metodo setAttributeNode() aggiunge il nodo attributo specificato a un elemento.
Se l'attributo specificato esiste già, questo metodo lo sostituisce.
Il valore restituito di questo metodo è un oggetto Attr. Per ulteriori informazioni, vedere L'oggetto attributo HTML DOM .
Vedi anche il metodo setAttribute() .
Suggerimento: utilizzare il metodo removeAttributeNode() per rimuovere un nodo di attributo da un elemento.
Supporto browser
Method | |||||
---|---|---|---|---|---|
setAttributeNode() | Yes | Yes | Yes | Yes | Yes |
Sintassi
element.setAttributeNode(attributenode)
Valori dei parametri
Parameter | Type | Description |
---|---|---|
attributenode | Attr object | Required. The attribute node you want to add |
Dettagli tecnici
Valore di ritorno: | Un oggetto Attr, che rappresenta il nodo dell'attributo sostituito, se presente, altrimenti nullo |
---|---|
Versione DOM | Oggetto elemento di livello 1 di base |
Altri esempi
Esempio
Imposta il nodo dell'attributo href di un elemento <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>
Prima di impostare il nodo attributo:
Go to w3schools.com
Dopo aver impostato il nodo attributo:
Pagine correlate
Esercitazione HTML: attributi HTML
Riferimento HTML DOM: l'oggetto attributo HTML DOM
Riferimento HTML DOM: metodo setAttribute()
Riferimento HTML DOM: metodo document.createAttribute()
Riferimento HTML DOM: attributo .value Proprietà
Riferimento HTML DOM: metodo getAttributeNode()
Riferimento HTML DOM: metodo removeAttributeNode()
❮ L'oggetto elemento