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 బ్రౌజర్ ఈ సెక్షన్ లో.