Skip to content
Advertisement

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.

Advertisement

Answer

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"]
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement