DOM Element
物件getElementByTagName()
方法給出指定元素的值。
語法
以下是使用getElementByTagName()
方法的語法。
getElementsByTagName(name)
引數
name
- 它包含要檢索的屬性的名稱。返回值
範例
檔案:node.xml 的內容如下 -
<?xml version = "1.0" encoding = "UTF-8" standalone = "no" ?>
<Company>
<Employee category = "Technical" id = "firstelement">
<FirstName>Susen</FirstName>
<LastName>Su</LastName>
<ContactNo>1584567890</ContactNo>
<Email>[email protected]</Email>
</Employee>
</Company>
以下範例演示了getElementByTagName()
方法的用法 -
<!DOCTYPE html>
<html>
<head>
<script></script>
</head>
<body>
<div>
<b>FirstName:</b> <span id = "FirstName"></span>
<b>LastName:</b> <span id = "LastName"></span>
<b>Category:</b> <span id = "Employee"></span>
</div>
<script>
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","/node.xml",false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
document.getElementById("FirstName").innerHTML=
xmlDoc.getElementsByTagName("FirstName")[0].childNodes[0].nodeValue;
document.getElementById("LastName").innerHTML=
xmlDoc.getElementsByTagName("LastName")[0].childNodes[0].nodeValue;
document.getElementById("Employee").innerHTML=
xmlDoc.getElementsByTagName("Employee")[0].attributes[0].nodeValue;
</script>
</body>
</html>
執行上面範例程式碼,得到以下結果 -