Metodo HTML DOM replaceChild()
Esempio
Sostituisci un nodo di testo in un elemento <li> in un elenco con un nuovo nodo di testo:
// 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"
Prima di sostituire:
- Coffee
- Tea
- Milk
Dopo la sostituzione:
- Water
- Tea
- Milk
Altri esempi "Provalo da solo" di seguito.
Definizione e utilizzo
Il metodo replaceChild() sostituisce un nodo figlio con un nuovo nodo.
Il nuovo nodo potrebbe essere un nodo esistente nel documento oppure puoi creare un nuovo nodo.
Suggerimento: usa il metodo removeChild() per rimuovere un nodo figlio da un elemento.
Supporto browser
Method | |||||
---|---|---|---|---|---|
replaceChild() | Yes | Yes | Yes | Yes | Yes |
Sintassi
node.replaceChild(newnode, oldnode)
Valori dei parametri
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 |
Dettagli tecnici
Valore di ritorno: | Un oggetto Node, che rappresenta il nodo sostituito |
---|---|
Versione DOM | Oggetto nodo di livello 1 principale |
Altri esempi
Esempio
Sostituisci un elemento <li> in un elenco con un nuovo 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
Prima di rimuovere:
- Coffee
- Tea
- Milk
Dopo aver rimosso:
- Water
- Tea
- Milk