Metoda HTML DOM replaceChild()
Przykład
Zastąp węzeł tekstowy w elemencie <li> na liście nowym węzłem tekstowym:
// 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"
Przed wymianą:
- Coffee
- Tea
- Milk
Po wymianie:
- Water
- Tea
- Milk
Więcej przykładów „Wypróbuj sam” poniżej.
Definicja i użycie
Metoda replaceChild() zastępuje węzeł podrzędny nowym węzłem.
Nowy węzeł może być istniejącym węzłem w dokumencie lub możesz utworzyć nowy węzeł.
Wskazówka: Użyj metody removeChild() , aby usunąć węzeł podrzędny z elementu.
Obsługa przeglądarki
Method | |||||
---|---|---|---|---|---|
replaceChild() | Yes | Yes | Yes | Yes | Yes |
Składnia
node.replaceChild(newnode, oldnode)
Wartości parametrów
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 |
Szczegóły techniczne
Wartość zwrotu: | Obiekt Node, reprezentujący zastępowany węzeł |
---|---|
Wersja DOM | Obiekt węzła poziomu podstawowego |
Więcej przykładów
Przykład
Zastąp element <li> na liście nowym elementem <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
Przed wyjęciem:
- Coffee
- Tea
- Milk
Po usunięciu:
- Water
- Tea
- Milk