4

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.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
user2302725
  • 463
  • 6
  • 20

2 Answers2

1

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;
}
Jérémie Bertrand
  • 3,025
  • 3
  • 44
  • 53
  • 1
    This code sure doesn't work as is. What is `this.xpath`? This fails when node becomes DOCUMENT as it does not have a hasAttribute method. – Charlie Apr 05 '21 at 04:31
0

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"]
ggorlen
  • 44,755
  • 7
  • 76
  • 106
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • I don't need to get element with his xpath, I would need to get the xpath of an element clicked. – user2302725 May 24 '13 at 09:32
  • Yeah, I know (you already have it). Please read the answer again. The *path* you are looking for is `//*[@id="THE_ID"]` – hek2mgl May 24 '13 at 09:33
  • Sounds like you are searching for the `DOM Path` rather then an XPath expression. (Although a DOM path is a valid XPath expression as well) Check [this question](http://stackoverflow.com/questions/5728558/jquery-get-the-dom-path-of-the-clicked-a) – hek2mgl May 24 '13 at 09:39
  • Yeah, that's I want. I think your explanation will help me to find a solution. Thank you. – user2302725 May 24 '13 at 10:01