Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i get the xpath of an element in an X/HTML file

I am a beginner to Xpath and was wondering if there is any way to get the xpath of an element in javascript/jquery. I need an absolute way to identify an element and I knw Xpath is used for this,but can't figure how.

The scenario is that I have a jquery reference of an element. I want its xpath to store in a database on mouse click. How do I get the Xpath of an HTML Element once I have a jquery reference. I need to be able to translate the Xpath into an absolute element later

function clickTrack(event){
offset=event.pageX;
var xpath=getXpath(this);//I need the xpath here
data={'xpath':xpath,'offset':offset};

}
like image 598
SoWhat Avatar asked Dec 06 '22 16:12

SoWhat


1 Answers

You can extract this functionality from an XPath tool I once wrote:

http://webkitchen.cz/lab/opera/xpath-tool/xpath-tool.js


Edit: here you go:

function getXPath(node) {
    var comp, comps = [];
    var parent = null;
    var xpath = '';
    var getPos = function(node) {
        var position = 1, curNode;
        if (node.nodeType == Node.ATTRIBUTE_NODE) {
            return null;
        }
        for (curNode = node.previousSibling; curNode; curNode = curNode.previousSibling) {
            if (curNode.nodeName == node.nodeName) {
                ++position;
            }
        }
        return position;
     }

    if (node instanceof Document) {
        return '/';
    }

    for (; node && !(node instanceof Document); node = node.nodeType == Node.ATTRIBUTE_NODE ? node.ownerElement : node.parentNode) {
        comp = comps[comps.length] = {};
        switch (node.nodeType) {
            case Node.TEXT_NODE:
                comp.name = 'text()';
                break;
            case Node.ATTRIBUTE_NODE:
                comp.name = '@' + node.nodeName;
                break;
            case Node.PROCESSING_INSTRUCTION_NODE:
                comp.name = 'processing-instruction()';
                break;
            case Node.COMMENT_NODE:
                comp.name = 'comment()';
                break;
            case Node.ELEMENT_NODE:
                comp.name = node.nodeName;
                break;
        }
        comp.position = getPos(node);
    }

    for (var i = comps.length - 1; i >= 0; i--) {
        comp = comps[i];
        xpath += '/' + comp.name;
        if (comp.position != null) {
            xpath += '[' + comp.position + ']';
        }
    }

    return xpath;

}

It might need some changes if you want it to work in IE as well.

like image 135
Jakub Roztocil Avatar answered Dec 09 '22 05:12

Jakub Roztocil