Created
March 8, 2013 19:00
-
-
Save MartijnR/5118908 to your computer and use it in GitHub Desktop.
Get XPath from jQuery element
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Creates an XPath from a node (currently not used inside this Class (instead FormHTML.prototype.generateName is used) but will be in future); | |
* @param {string=} rootNodeName if absent the root is #document | |
* @return {string} XPath | |
*/ | |
$.fn.getXPath = function(rootNodeName){ | |
//other nodes may have the same XPath but because this function is used to determine the corresponding input name of a data node, index is not included | |
var position, | |
$node = this.first(), | |
nodeName = $node.prop('nodeName'), | |
$sibSameNameAndSelf = $node.siblings(nodeName).addBack(), | |
steps = [], | |
$parent = $node.parent(), | |
parentName = $parent.prop('nodeName'); | |
position = ($sibSameNameAndSelf.length > 1) ? '['+($sibSameNameAndSelf.index($node)+1)+']' : ''; | |
steps.push(nodeName+position); | |
while ($parent.length == 1 && parentName !== rootNodeName && parentName !== '#document'){ | |
$sibSameNameAndSelf = $parent.siblings(parentName).addBack(); | |
position = ($sibSameNameAndSelf.length > 1) ? '['+($sibSameNameAndSelf.index($parent)+1)+']' : ''; | |
steps.push(parentName+position); | |
$parent = $parent.parent(); | |
parentName = $parent.prop('nodeName'); | |
} | |
return '/'+steps.reverse().join('/'); | |
}; |
I am trying to implement your function however getting not an xpath, would you please you help me?
I always get "/undefined", what does this do exactly?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://gist.github.com/iimos/e9e96f036a3c174d0bf4