javascript - How to get the xpath by clicking an html element -
i quite new programming , have generate xpath on clicking html element. example :if have clicked on text box of username should give me xpath html/head/body/tr[1]/table[2]..... etc etc. main thing can not use firebug application thoroughly goin run on ie. have seen lot of fxn xpath , tried integrate not getting return value. simple code snippet used jquery click() function retrieve value not working.the thing unable pass html element in function.the xpath function have taken site only. code 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 1 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 = ''; ( ; 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>
change script to
$( "#test" ).click(function() { var value= getxpath( ); alert(value) }); function getxpath( element ) { var val=element.value; //alert("val="+val); var xpath = ''; ( ; 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; }
Comments
Post a Comment