XML DOM replaceChild() 方法
定义和用法
replaceChild() 方法用其他节点替换某个子节点。
如成功,该方法返回被替换的节点,如失败,则返回 null。
语法:
elementNode.replaceChild(new_node,old_node)
参数 | 描述 |
---|---|
new_node | 必需。规定新的节点。 |
old_node | 必需。规定要替换的子节点。 |
实例
在所有的例子中,我们将使用 XML 文件 books.xml,以及 JavaScript 函数 loadXMLDoc()。
下面的代码片段替换 "books.xml" 中第一个 <book> 元素的第一个 <title> 元素:
//check if first child node is an element node
function get_firstchild(n)
{
x=n.firstChild;
while (x.nodeType!=1)
{
x=x.nextSibling;
}
return x;
}
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("book")[0];
//create a title element and a text node
newNode=xmlDoc.createElement("title");
newText=xmlDoc.createTextNode("Giada's Family Dinners");
//add the text node to the title node,
newNode.appendChild(newText);
//replace the last node with the new node
x.replaceChild(newNode,get_firstchild(x));
y=xmlDoc.getElementsByTagName("title");
for (i=0;i<y.length;i++)
{
document.write(y[i].childNodes[0].nodeValue);
document.write("<br />");
}
ການອອກພາບ:
Giada's Family Dinners Harry Potter XQuery Kick Start Learning XML
ຄວາມເຫັນ:Internet Explorer ຈະຂາດຫຼັກກິດຈັກກາງຫຼັກກິດ (ອີງວ່າ, ສັນຍາວັນ) ທີ່ສ້າງຂຶ້ນລະຫວ່າງຫຼັກກິດ, ແຕ່ Mozilla ຈະບໍ່ເຮັດແນວນັ້ນ. ເພາະດັ່ງນັ້ນ, ພວກເຮົາໄດ້ສ້າງຫົວຫຼັກກິດຂອງພວກເຮົາເພື່ອສ້າງຫຼັກກິດລູກຄວາມທີ່ຖືກຕ້ອງ.
ຄຳເຕືອນ:ສຳລັບຂໍ້ມູນກ່ຽວກັບຄວາມແຕກຕ່າງລະຫວ່າງ IE ແລະ Mozilla ສະເພາະນັກຄົ້ນຫາ, ກະລຸນາເຂົ້າມາທີ່ CodeW3C.com XML DOM 教程. DOM ສະເພາະນັກຄົ້ນຫາ ບົດນີ້.