Skip to content

Instantly share code, notes, and snippets.

@MartijnR
Created March 8, 2013 19:00
Show Gist options
  • Save MartijnR/5118908 to your computer and use it in GitHub Desktop.
Save MartijnR/5118908 to your computer and use it in GitHub Desktop.
Get XPath from jQuery element
/**
* 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('/');
};
@iimos
Copy link

iimos commented Sep 17, 2015

@ogarciacapetillo
Copy link

I am trying to implement your function however getting not an xpath, would you please you help me?

@adelriosantiago
Copy link

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