Método HTML DOM setAttributeNode()
❮ O Objeto ElementoExemplo
Defina o nó de atributo de classe de um 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>
Antes de definir o nó de atributo:
Hello World
Depois de definir o nó de atributo:
Hello World
Mais exemplos de "Experimente você mesmo" abaixo.
Definição e uso
O método setAttributeNode() adiciona o nó de atributo especificado a um elemento.
Se o atributo especificado já existir, este método o substituirá.
O valor de retorno desse método é um objeto Attr. Para obter mais informações, consulte O objeto de atributo HTML DOM .
Veja também o método setAttribute() .
Dica: Use o método removeAttributeNode() para remover um nó de atributo de um elemento.
Suporte ao navegador
Method | |||||
---|---|---|---|---|---|
setAttributeNode() | Yes | Yes | Yes | Yes | Yes |
Sintaxe
element.setAttributeNode(attributenode)
Valores de parâmetro
Parameter | Type | Description |
---|---|---|
attributenode | Attr object | Required. The attribute node you want to add |
Detalhes técnicos
Valor de retorno: | Um objeto Attr, representando o nó de atributo substituído, se houver, caso contrário, nulo |
---|---|
Versão DOM | Objeto de elemento de nível 1 principal |
Mais exemplos
Exemplo
Defina o nó do atributo href de um 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>
Antes de definir o nó de atributo:
Go to w3schools.com
Depois de definir o nó de atributo:
Páginas relacionadas
Tutorial HTML: Atributos HTML
Referência HTML DOM: o objeto de atributo HTML DOM
Referência HTML DOM: método setAttribute()
Referência HTML DOM: método document.createAttribute()
Referência HTML DOM: atributo .value Propriedade
Referência HTML DOM: método getAttributeNode()
Referência HTML DOM: método removeAttributeNode()
❮ O Objeto Elemento