Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 540
user2302725 Avatar asked Nov 26 '25 04:11

user2302725


1 Answers

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;
}
like image 190
John Hudson Avatar answered Nov 27 '25 19:11

John Hudson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!