DOM - 元素物件方法 - getAttribute



getAttribute 方法如果存在指定元素的屬性,則返回該屬性的值。

語法

以下是 getAttribute 方法用法的語法。

elementObj.getAttribute(name)

序號 引數及描述
1

名稱

它儲存要檢索的屬性的名稱。

如果存在,此方法將屬性值作為字串返回,否則將指定為 null。

示例

node.xml 內容如下:

<?xml version = "1.0"?>
<Company>
   <Employee category = "Technical">
      <FirstName>Tanmay</FirstName>
      <LastName>Patil</LastName>
      <ContactNo>1234567890</ContactNo>
      <Email>tanmaypatil@xyz.com</Email>
   </Employee>
   
   <Employee category = "Non-Technical">
      <FirstName>Taniya</FirstName>
      <LastName>Mishra</LastName>
      <ContactNo>1234667898</ContactNo>
      <Email>taniyamishra@xyz.com</Email>
   </Employee>
   
   <Employee category = "Management">
      <FirstName>Tanisha</FirstName>
      <LastName>Sharma</LastName>
      <ContactNo>1234562350</ContactNo>
      <Email>tanishasharma@xyz.com</Email>
   </Employee>
</Company>

以下示例演示了 getAttribute 方法的用法:

<!DOCTYPE html>
<html>
   <body>
      <script>
         if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
         } else {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
         }
         xmlhttp.open("GET","/dom/node.xml",false);
         xmlhttp.send();
         xmlDoc = xmlhttp.responseXML;
         x = xmlDoc.getElementsByTagName('Employee')[2];
         document.write("The attribute is: ");
         document.write(x.getAttribute('category'));

      </script>
   </body>
</html>

執行

將此檔案儲存為伺服器路徑上的 elementattribute_getattribute.html(此檔案和 node.xml 應位於伺服器上的同一路徑)。我們將得到如下所示的輸出:

The attribute is: Management
dom_element_object.htm
廣告

© . All rights reserved.