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>
XML and HTML Note that HTML and XML have a very similar structure, which is why XPath can be used almost interchangeably to navigate both HTML and XML documents.
To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked. Here is the HTML for the examples in this article.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With