user2302725
user2302725

Reputation: 473

Get element's xpath in javascript

I am developing in javascript and I would need to get the xpath of the element clicked. I know that in order to get the id we can do :

element.onclick = function(event)
{
    var target_id = event.target.id;
}

How could I do to get the xpath ?

Regards.

Upvotes: 4

Views: 8358

Answers (2)

hek2mgl
hek2mgl

Reputation: 157927

There are many ways to access an element with XPath. For example you can access it by node name or by the value of one of it's attributes or child nodes. So you can not expect that javascript gives you exactly one of them.

But as you have the id, the simplest xpath query to access the element would be:

//*[@id="THE_ID"]

Upvotes: 0

John Hudson
John Hudson

Reputation: 83

Here:

function getXPath(node){
    if(node.hasAttribute("id")){
        return '//' + node.tagName + '[@id="' + node.id + '"]';
    }

    if(node.hasAttribute("class")){
        return '//' + node.tagName + '[@class="' + node.getAttribute("class") + '"]';
    }

    var old = '/' + node.tagName;
    var new_path = this.xpath(node.parentNode) + old;

    return new_path;
}

Upvotes: 1

Related Questions