简体   繁体   English

如何在javascript中按元素查找Xpath

[英]How to find the Xpath by element in javascript

Everyone knows to find a element using Xpath, there are multiple tools there to find the element.每个人都知道使用 Xpath 查找元素,那里有多种工具可以查找元素。 But I have the element.但我有这个元素。 But how to find the xpath for that element using javascript.但是如何使用 javascript 找到该元素的 xpath。 Is there any way to find the Xpath.有什么办法可以找到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);

There is a comment on SO page , which probably might help you: SO page 上一条评论,可能会对您有所帮助:

 // 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演示 - https://codepen.io/vyspiansky/pen/abNpOoE?editors=1111

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何为使用Javascript工具提示定义的Web元素查找Xpath? - How to find Xpath for a web element defined using a Javascript tooltip? 使用JavaScript和/或JQuery,如何找到“ XPath”或映射到元素? - Using JavaScript and/or JQuery, how can I find the “XPath” or map to an element? 如何找到xpath到图像元素 - How to find xpath to the image element 如何找到动态 xpath 元件 - How to find dinamic xpath element 通过IE11上的xPath查找元素。 JavaScript的 - To find element by xPath on IE11. JavaScript 如何在 JavaScript 中通过 XPATH 获取元素? - How to get Element by XPATH in JavaScript? 如何从带有 javascript 的网站单击按钮并通过 xpath 和该元素包含的特定文本找到该元素? - How to click a button from a website with javascript and find that element through xpath and a specific text that the element contains? 如何通过QTP中的iframe通过xpath查找元素 - How to find element by xpath from iframe in QTP How to find web element by xpath using javascript code in python selenium webdriver? - How to find web element by xpath using javascript code in python selenium webdriver? 如何使用 Javascript 计算元素的 XPath 位置? - How to calculate the XPath position of an element using Javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM