Monday, December 19, 2011

Get XPATH of element in IE

Ever had the need to get the XPATH of an element and you are using IE.  Well, here is how you can:  Create a bookmarklet with the following javascript:

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;}function getXPATH(){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);}getXPATH();

Bookmarklets are just a simple bookmark and you use the script as the url to the site instead of an actual url.  Hope someone else finds this useful.

The code above was adapted from http://functionaltestautomation.blogspot.com/2008/12/xpath-in-internet-explorer.html


No comments:

Post a Comment