最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get the xpath by clicking an html element - Stack Overflow

programmeradmin6浏览0评论

I am quite new to programming and have to generate a Xpath on clicking an html element. for example :if i have clicked on text box of username then it should give me the xpath like html/head/body/tr[1]/table[2]..... etc etc. The main thing is i can not use firebug as my application is thoroughly goin to run on IE. I have seen lot of fxn to get xpath and tried to integrate it but i am not getting the return value. A simple code snippet where i used jquery click() function to retrieve the value is not working.The thing is i am unable to pass the html element in the function.The xpath function i have taken from this site only. My code is below.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>click demo</title>
<style> 
p
{ 
   color: red;    
   margin: 5px;
   cursor: pointer; 
}  
p:hover
 { 
   background: yellow; 
 }
</style> 
<script src=".9.1.js">
</script>
</head>
<body> 
<p id ="test">First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
<script>

$( "#test" ).click(function() { var value= $(this).getXPath();
alert(value) });

function getXPath( element )
{
var val=element.value;
alert("val="+val);
    var xpath = '';
    for ( ; element && element.nodeType == 1; element = element.parentNode )
    {
        alert(element);
        var id = $(element.parentNode).children(element.tagName).index(element) + 1;
        id > 1 ? (id = '[' + id + ']') : (id = '');
        xpath = '/' + element.tagName.toLowerCase() + id + xpath;
    }
    return xpath;
}
</script>
</body>
</html> 

I am quite new to programming and have to generate a Xpath on clicking an html element. for example :if i have clicked on text box of username then it should give me the xpath like html/head/body/tr[1]/table[2]..... etc etc. The main thing is i can not use firebug as my application is thoroughly goin to run on IE. I have seen lot of fxn to get xpath and tried to integrate it but i am not getting the return value. A simple code snippet where i used jquery click() function to retrieve the value is not working.The thing is i am unable to pass the html element in the function.The xpath function i have taken from this site only. My code is below.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>click demo</title>
<style> 
p
{ 
   color: red;    
   margin: 5px;
   cursor: pointer; 
}  
p:hover
 { 
   background: yellow; 
 }
</style> 
<script src="http://code.jquery.com/jquery-1.9.1.js">
</script>
</head>
<body> 
<p id ="test">First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
<script>

$( "#test" ).click(function() { var value= $(this).getXPath();
alert(value) });

function getXPath( element )
{
var val=element.value;
alert("val="+val);
    var xpath = '';
    for ( ; element && element.nodeType == 1; element = element.parentNode )
    {
        alert(element);
        var id = $(element.parentNode).children(element.tagName).index(element) + 1;
        id > 1 ? (id = '[' + id + ']') : (id = '');
        xpath = '/' + element.tagName.toLowerCase() + id + xpath;
    }
    return xpath;
}
</script>
</body>
</html> 
Share Improve this question asked Sep 4, 2013 at 6:22 PiyushPiyush 3881 gold badge8 silver badges21 bronze badges 2
  • why did you delete the question about ObservableList? I can provide an example of how I would do that – Andrew Commented Jul 20, 2018 at 10:18
  • I have done a very silly mistake....so deleted it.... but i will un-delete it to have better suggestions... thanks for the same. – Piyush Commented Jul 20, 2018 at 10:29
Add a comment  | 

4 Answers 4

Reset to default 23

change script to

$( "#test" ).click(function() { var value= getXPath( this  );
alert(value) });

function getXPath( element )
{
var val=element.value;
    //alert("val="+val);
    var xpath = '';
    for ( ; element && element.nodeType == 1; element = element.parentNode )
    {
        //alert(element);
        var id = $(element.parentNode).children(element.tagName).index(element) + 1;
        id > 1 ? (id = '[' + id + ']') : (id = '');
        xpath = '/' + element.tagName.toLowerCase() + id + xpath;
    }
    return xpath;
}

This could help you

fiddle

$('p').click(function(){
parentEls = $(this).parents()
            .map(function () {
                  return this.tagName;
                })
            .get().join(", ");

    alert(parentEls);

    });

In IE You need to insatll Bookmarklets.

STEPS TO INSTAL BOOKMARKLETS

1)Open IE

2)Type about:blank in the address bar and hit enter

3)From Favorites main menu select--->Add favorites

4) In the Add a favorite popup window enter name GetXPATH1.

5)Click add button in the add a favorite popup window.

6)Open the Favorites menu and right click the newly added favorite and select properties option.

7)GetXPATH1 Properties will open up. Select the web Document Tab.

8)Enter the following in the URL field.

javascript:function getNode(node){var nodeExpr=node.tagName;if(!nodeExpr)return null;if(node.id!=''){nodeExpr+="[@id='"+node.id+"']";return "/"+nodeExpr;}var rank=1;var ps=node.previousSibling;while(ps){if(ps.tagName==node.tagName){rank++;}ps=ps.previousSibling;}if(rank>1){nodeExpr+='['+rank+']';}else{var ns=node.nextSibling;while(ns){if(ns.tagName==node.tagName){nodeExpr+='[1]';break;}ns=ns.nextSibling;}}return nodeExpr;}

9)Click Ok. Click YES on the popup alert.

10)Add another favorite by following steps 3 to 5, Name this favorite GetXPATH2 (step4)

11)Repeat steps 6 and 7 for GetXPATH2 that you just created.

12)Enter the following in the URL field for GetXPATH2

javascript:function o_o(){var currentNode=document.selection.createRange().parentElement();var path=[];while(currentNode){var pe=getNode(currentNode);if(pe){path.push(pe);if(pe.indexOf('@id')!=-1)break;}currentNode=currentNode.parentNode;}var xpath="/"+path.reverse().join('/');clipboardData.setData("Text", xpath);}o_o();

13)Repeat Step 9.

You are all done!!

Now to get the XPATH of elements just select the element with your mouse. This would involve clicking the left mouse button just before the element (link, button, image, checkbox, text etc) begins and dragging it till the element ends. Once you do this first select the favorite GetXPATH1 from the favorites menu and then select the second favorite GetXPATH2. At his point you will get a confirmation, hit allow access button. Now open up a notepad file, right click and select paste option. This will give you the XPATH of the element you seek.

This code give path of element.

      $('a').click(function () {
            var XPATH = "";
            var FindParent = true;
            var _parent = $(this);

            while (FindParent) {
                var myParent = _parent.parent();
                if (myParent != null) {
                    XPATH += myParent.prop("tagName") + "/";
                    _parent = myParent;
                }
                else {
                    FindParent = false;
                }

            }
        })
发布评论

评论列表(0)

  1. 暂无评论