bozhidarc
bozhidarc

Reputation: 854

Extracting XPath query for a given element

Is there a way to be extracted the XPath query string with javascript for a given element, like the firebug "Copy XPath" functionality.

Thanks

Upvotes: 1

Views: 166

Answers (1)

anton_byrna
anton_byrna

Reputation: 2555

Did you mean that you need something like this:

var getXPath = function(aNode) {
    var xpath = '', prevSibling = aNode, position = 1, nodeType = aNode.nodeType, nodeName = aNode.nodeName;

    while (prevSibling = prevSibling.previousSibling) {
        if (prevSibling.nodeType == nodeType && prevSibling.nodeName == nodeName) {
            position += 1;
        }
    }

    xpath = ((nodeType == 3 /* TEXT_NODE */) ? 'text()' : nodeName) + '[' + position + ']' + (xpath.length ? '/' + xpath : '');

    if (aNode.parentNode && aNode.parentNode.nodeName != 'BODY') {
        return xpath = (getXPath(aNode.parentNode, xpath) + '/' + xpath).toLowerCase();
    }

    return xpath;
};

Upvotes: 2

Related Questions