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 នឹងមិនធ្វើដូច្នេះ ដូច្នេះ ក្នុងឧទាហរណ៍ខាងលើ ពួកយើងបានបង្កើតការបន្ថែមមួយដើម្បីបង្កើតតំណាងកូនដែលត្រឹមត្រូវ
ការណែនាំ:សំរាប់ពត៌មានអំពីភាពខុសគ្នារវាង Internet Explorer និង Mozilla កម្មវិធីអត្ថបទ នៅក្នុង XML DOM កម្មវិធីអត្ថបទរបស់ CodeW3C.com កម្មវិធីអត្ថបទ ការបញ្ចាំងនេះ