Método HTML DOM replaceChild()
Exemplo
Substitua um nó de texto em um elemento <li> em uma lista por um novo nó de texto:
// Create a new text node called "Water"
var textnode = document.createTextNode("Water");
// Get the first child node of an <ul> element
var item = document.getElementById("myList").childNodes[0];
// Replace the first child node of <ul> with the newly created text node
item.replaceChild(textnode, item.childNodes[0]);
// Note: This example replaces only the Text node "Coffee" with a Text node "Water"
Antes de substituir:
- Coffee
- Tea
- Milk
Depois de substituir:
- Water
- Tea
- Milk
Mais exemplos de "Experimente você mesmo" abaixo.
Definição e uso
O método replaceChild() substitui um nó filho por um novo nó.
O novo nó pode ser um nó existente no documento ou você pode criar um novo nó.
Dica: Use o método removeChild() para remover um nó filho de um elemento.
Suporte ao navegador
Method | |||||
---|---|---|---|---|---|
replaceChild() | Yes | Yes | Yes | Yes | Yes |
Sintaxe
node.replaceChild(newnode, oldnode)
Valores de parâmetro
Parameter | Type | Description |
---|---|---|
newnode | Node object | Required. The node object you want to insert |
oldnode | Node object | Required. The node object you want to remove |
Detalhes técnicos
Valor de retorno: | Um objeto Node, representando o nó substituído |
---|---|
Versão DOM | Objeto de nó de nível 1 principal |
Mais exemplos
Exemplo
Substitua um elemento <li> em uma lista por um novo elemento <li>:
// Create a new <li> element
var elmnt = document.createElement("li");
// Create a new text node called "Water"
var textnode = document.createTextNode("Water");
// Append the text node to <li>
elmnt.appendChild(textnode);
// Get the <ul> element with id="myList"
var item = document.getElementById("myList");
// Replace the first child node (<li> with index 0) in <ul> with the newly created <li> element
item.replaceChild(elmnt, item.childNodes[0]);
// Note: This example replaces the entire <li> element
Antes de remover:
- Coffee
- Tea
- Milk
Após remover:
- Water
- Tea
- Milk