獲取html元素的XPath路徑


 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <script src="/jquery/jquery-1.11.1.min.js">
 5 </script>
 6 <script>
 7 
 8  function readXPath(element) {
 9     if (element.id! == ""){//判斷id屬性,如果這個元素有id,則顯 示//*[@id="xPath"]  形式內容
10         return '//*[@id=\"'+element.id+'\"]';
11     }
12 
13     if (element.getAttribute("class")! == null){ //判斷class屬性,如果這個元素有class,則顯 示//*[@class="xPath"]  形式內容
14         return '//*[@class=\"'+element.getAttribute("class")+'\"]';
15     }
16     //因為Xpath屬性不止id和class,所以還可以更具class形式添加屬性
17 
18     //這里需要需要主要字符串轉譯問題
19 
20 
21     if (element == document.body){//遞歸到body處,結束遞歸
22         return '/html/'+element.tagName.toLowerCase();
23     }
24 
26     var ix= 0,//在nodelist中的位置,且每次點擊初始化
27           siblings= element.parentNode.childNodes;//同級的子元素
28 
29     for (var i= 0,l=siblings.length; i<l; i++) {
30         var sibling = siblings[i];
31         if (sibling == element){//如果這個元素是siblings數組中的元素,則執行遞歸操作
32             return arguments.callee(element.parentNode)+'/'+element.tagName.toLowerCase()+((ix+1)==1?'':'['+(ix+1)+']');//ix+1是因為xpath是從1開始計數的,element.tagName+((ix+1)==1?'':'['+(ix+1)+']')三元運算符,如果是第一個則不顯示,從2開始顯示
33         }else if(sibling.nodeType == 1 && sibling.tagName == element.tagName){//如果不符合,判斷是否是element元素,並且是否是相同元素,如果是相同的就開始累加
34             ix++;
35         }
36     }
37 };
38 
39 $(document).ready(function () {
40     var xpath = '', o;
41     $('*').click(function (e) {
42         e.stopPropagation();//停止冒泡
43         o = this;
44         alert(readXPath(o));
45     });
46 });
47 
48 </script>
49 </head>
50 <body>
51 <p>如果您點擊我,我會消失。</p>
52 <p>點擊我,我會消失。</p>
53 <p>也要點擊我哦。</p>
54 </body>
55 </html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM