How to get the xpath by clicking an html element
15,913
Solution 1
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;
}
Solution 2
This could help you
$('p').click(function(){
parentEls = $(this).parents()
.map(function () {
return this.tagName;
})
.get().join(", ");
alert(parentEls);
});
Author by
Piyush
Updated on June 06, 2022Comments
-
Piyush about 2 years
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>