在本章中,我们将讨论已存在元素的节点。在这节中将学习添加(或插入)新节点 -
appendChild()
insertBefore()
insertData()
1. 使用appendChild()方法
方法appendChild()
用于向现有子节点之后添加新的子节点。
语法
appendChild()
方法的语法如下 -
Node appendChild(Node newChild) throws DOMException
其中,
示例
以下示例(append_childnode.html)将XML文档(node.xml)解析为XML DOM对象,并将新的子元素PhoneNo
附加到元素 - <FirstName>
。
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc(filename) {
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else{ // code for IE5 and IE6
xhttp = new ActiveXObject(Microsoft.XMLHTTP);
}
xhttp.open(GET,filename,false);
xhttp.send();
return xhttp.responseXML;
}
</script>
</head>
<body>
<script>
xmlDoc = loadXMLDoc(/node.xml);
create_e = xmlDoc.createElement(PhoneNo);
x = xmlDoc.getElementsByTagName(FirstName)[0];
x.appendChild(create_e);
document.write(x.getElementsByTagName(PhoneNo)[0].nodeName);
</script>
</body>
</html>
在上面的例子中 -
执行
运行上面示例代码,得到以下结果 -
2. insertBefore()方法
insertBefore()
方法在指定的子节点之前插入新的子节点。
语法insertBefore()
方法的语法如下 -
Node insertBefore(Node newChild, Node refChild) throws DOMException
其中,
newChild
- 要插入的节点refChild
- 是引用节点,即必须在其之前插入新节点的节点。- 此方法返回要插入的节点。
示例
以下示例(insert_nodebefore.html)将XML文档(node.xml)解析为XML DOM对象,并在指定元素<Email>
之前插入新的子元素:Email
。
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc(filename) {
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else{ // code for IE5 and IE6
xhttp = new ActiveXObject(Microsoft.XMLHTTP);
}
xhttp.open(GET,filename,false);
xhttp.send();
return xhttp.responseXML;
}
</script>
</head>
<body>
<script>
xmlDoc = loadXMLDoc(/node.xml);
create_e = xmlDoc.createElement(Email);
x = xmlDoc.documentElement;
y = xmlDoc.getElementsByTagName(Email);
document.write(No of Email elements before inserting was: + y.length);
document.write(<br>);
x.insertBefore(create_e,y[3]);
y=xmlDoc.getElementsByTagName(Email);
document.write(No of Email elements after inserting is: + y.length);
</script>
</body>
</html>
在上面的例子中 -
执行上面示例代码,得到以下结果 -
3. insertData()方法
insertData()
方法在指定的16
位单位偏移处插入一个字符串。
语法insertData()
的语法如下 -
void insertData(int offset, java.lang.String arg) throws DOMException
其中,
offset
- 是要插入的字符偏移量。arg
- 是插入数据的关键词。它用括号括起两个参数:offset
和arg
,用逗号分隔。
示例
以下示例(addtext.html)将XML文档(node.xml
)解析为XML DOM对象,并将指定位置的新数据MiddleName
插入到元素<FirstName>
。
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc(filename) {
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else{ // code for IE5 and IE6
xhttp = new ActiveXObject(Microsoft.XMLHTTP);
}
xhttp.open(GET,filename,false);
xhttp.send();
return xhttp.responseXML;
}
</script>
</head>
<body>
<script>
xmlDoc = loadXMLDoc(/node.xml);
x = xmlDoc.getElementsByTagName(FirstName)[0].childNodes[0];
document.write(x.nodeValue);
x.insertData(3,MiddleName);
document.write(<br>);
document.write(x.nodeValue);
</script>
</body>
</html>
执行上面示例代码,得到以下结果 -