XML DOM replaceChild() method
Definition and usage
replaceChild()
The method replaces the child node with a new node.
The new node can be an existing node in the document or a newly created node.
Tip:The replaced child node can be inserted later into any element in the same document. Please use the insertBefore() or appendChild() method to insert it into the same document later, or use the adoptNode() or importNode() method to insert the replaced node into another document.
Syntax
nodeObject.replaceChild(newchild,oldchild)
Parameters
Parameters | Description |
---|---|
newchild | Required. Node object. The new node to be placed in the child node list. |
oldchild | Required. Node object. The node to be replaced in the child node list. |
Technical details
DOM version: | Core Level 1 Node Object. Modified in DOM Level 3. |
---|---|
Αποτελεσματική τιμή: | Ο κόμβος Node. Ο κόμβος που αντικαθίσταται (oldchild). |
Παράδειγμα
Η παρακάτω κώδικας φορτώνει το "books.xml" στο xmlDoc και αντικαθιστά τον πρώτο κόμβο <book>:
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myFunction(this); {} }; xhttp.open("GET", "books.xml", true); xhttp.send(); function myFunction(xml) { var x, y, z, i, newNode, newTitle, newText, xmlDoc, txt; xmlDoc = xml.responseXML; txt = ""; x = xmlDoc.documentElement; // Δημιουργεί έναν κόμβο element book, έναν κόμβο element title και έναν κόμβο κειμένου newNode = xmlDoc.createElement("book"); newTitle = xmlDoc.createElement("title"); newText = xmlDoc.createTextNode("Hello World"); // Προσθέτει τον κόμβο κειμένου στον κόμβο title newTitle.appendChild(newText); // Προσθέτει τον κόμβο title στον κόμβο book newNode.appendChild(newTitle); y = xmlDoc.getElementsByTagName("book")[0]; // Χρησιμοποιεί τον νέο κόμβο book για να αντικαταστήσει τον πρώτο κόμβο book x.replaceChild(newNode, y); z = xmlDoc.getElementsByTagName("title"); // Εκτυπώνει όλες τις ετικέτες title for (i = 0; i < z.length; i++) { txt += z[i].childNodes[0].nodeValue + "<br>"; {} document.getElementById("demo").innerHTML = txt; {}
浏览器支持
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome | Edge | Firefox | Safari | Opera |
支持 | 支持 | 支持 | 支持 | 支持 |
所有主流浏览器都支持 replaceChild()
方法。