ilinsky / jquery-xpath

jQuery XPath plugin (with full XPath 2.0 language support)
180 stars 64 forks source link

Feature Request: Get XPath of a Node #26

Closed cstayyab closed 3 years ago

cstayyab commented 4 years ago

Can we get XPath of an element when nothing is passed in the xpath() just like when we don't pass any value to val() we get its current value. I had something like this in mind:

inputNode = $("input")[0];
$(inputNode).xpath(); // should return "/html[1]/body[1]/input[1]"
ilinsky commented 3 years ago

Hi Muhammad,

The functionality you are looking for has very little to do with the purpose of the library. Your needs can easily be met with a simple function, see quick prototype in vanilla javascript:

function getXPathForElement(element) {
    var path = [];
    for (; element && element.nodeType != 9; element = element.parentNode) {
        for (var sibling = element, index = 1; sibling = sibling.previousSibling;) {
            if (sibling.nodeName == element.nodeName) {
                index++;
            }
        }
        path.unshift(element.localName + "[" + index + "]");
    }
    return '/' + path.join("/");
}