0

Everyone knows to find a element using Xpath, there are multiple tools there to find the element. But I have the element. But how to find the xpath for that element using javascript. Is there any way to find the Xpath.

document.addEventListener('click', function(e) {
    
    e = e || window.event;
    var target = e.target || e.srcElement,
        text = target.textContent || target.innerText;   
        alert(target.srcElement);
       
}, false);
Thiya
  • 75
  • 6

1 Answers1

0

There is a comment on SO page, which probably might help you:

// Returns XPATH to element
function getPathTo(element) {
    if (element.tagName == 'HTML')
        return '/HTML[1]';
    if (element===document.body)
        return '/HTML[1]/BODY[1]';

    var ix= 0;
    var siblings= element.parentNode.childNodes;
    for (var i= 0; i<siblings.length; i++) {
        var sibling= siblings[i];
        if (sibling===element)
            return getPathTo(element.parentNode)+'/'+element.tagName+'['+(ix+1)+']';
        if (sibling.nodeType===1 && sibling.tagName===element.tagName)
            ix++;
    }
}

// Usage examples:

const spanElem = getPathTo(document.getElementById('mySpan'));
console.log(spanElem);
// Output: "/HTML[1]/BODY[1]/DIV[1]/SPAN[1]"

const iElem = getPathTo(document.getElementsByTagName('i')[0]);
console.log(iElem);
// Output: "/HTML[1]/BODY[1]/DIV[1]/I[1]"
<div>
  <span id="mySpan">Some</span>
  <i>test</i>
</div>

Demo - https://codepen.io/vyspiansky/pen/abNpOoE?editors=1111

Anton
  • 2,669
  • 1
  • 7
  • 15
Ihor Vyspiansky
  • 918
  • 1
  • 6
  • 11