DOM-节点对象属性-previousSibling



属性 previousSibling 指定紧挨当前节点之前的节点。

语法

以下是previousSibling属性用法的语法。

nodeObject.previousSibling

示例

node.xml 内容如下所示 −

<?xml version = "1.0"?>
<Company>
   <Employee category = "Technical">
      <FirstName>Tanmay</FirstName>
      <LastName>Patil</LastName>
      <ContactNo>1234567890</ContactNo>
      <Email>[email protected]</Email>
   </Employee>
   
   <Employee category = "Non-Technical">
      <FirstName>Taniya</FirstName>
      <LastName>Mishra</LastName>
      <ContactNo>1234667898</ContactNo>
      <Email>[email protected]</Email>
   </Employee>
   
   <Employee category = "Management">
      <FirstName>Tanisha</FirstName>
      <LastName>Sharma</LastName>
      <ContactNo>1234562350</ContactNo>
      <Email>[email protected]</Email>
   </Employee>
</Company>

以下示例演示了previousSibling属性的用法 −

<!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;

         function get_previousSibling(p) {
            a = p.previousSibling;
            while (a.nodeType != 1) {
               a = a.previousSibling;
            }
            return a;
         }

         x = get_previousSibling(xmlDoc.getElementsByTagName("Email")[0]);
         document.write("Previous sibling of Email is : ");
         document.write(x.nodeName);
      </script>
   </body>
</html>

执行

将此文件另存为nodeattribute_previoussibling.htm,放在服务器路径中(此文件和node.xml应该在服务器中的同一个路径)。我们将会得到如下所示的输出 −

Previous sibling of Email is : ContactNo
dom_node_object.htm
广告