如何使用Javascript或Jquery创建单击元素的Xpath?

时间:2018-11-14 12:15:04

标签: javascript jquery html xpath

我有一个网页,其中将单击事件绑定到元素上。用户单击特定元素时。我想从html或body标签开始生成元素的XPath。即“绝对Xpath”

假设在下面的html示例中,我单击跨度为“ USA”的文本,因此绝对Xpath

/html[1]/body[1]/div[2]/div[1]/div[1]/span[1]
<html>
    <body>
        <div class="header">Countries</div>
        <div class="row">
            <div class="row_in">
                <div class="row_in_in">
                    <span>India</span>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="row_in">
                <div class="row_in_in">
                    <span>USA</span>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="row_in">
                <div class="row_in_in">
                    <span>UK</span>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="row_in">
                <div class="row_in_in">
                    <span>France</span>
                </div>
            </div>
        </div>
    </body>
</html>

我们是否有任何库可在其中帮助我生成XPath并将元素Dom传递给XPath?

我遇到了几个库,但是这些库基于提供的Xpath帮助检测html内的内容。

1 个答案:

答案 0 :(得分:1)

您需要遍历clicked元素及其父元素来完成此工作。因此,您可以调用函数嵌套来完成这项工作。

var xpath;
$("*").click(function(e){
  xpath = '';
  addXpath($(this));
  console.log(xpath);
  e.stopPropagation();
});

function addXpath($ele){
  var tagName = $ele[0].tagName.toLowerCase();
  var index = $ele.parent().children(tagName).index($ele)+1;
  xpath = '/'+tagName +'['+index+']'+ xpath;
  !$ele.parent().is(document) ? addXpath($ele.parent()) : "";
}
body {background: green}
.header {background: orange}
.row_in {background: yellow}
.row_in_in {background: blue}
span {background: red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="header">Countries</div>
<div class="row">
<div class="row_in">
  <div class="row_in_in">
    <span>India</span>
  </div>
</div>
</div>
<div class="row">
<div class="row_in">
  <div class="row_in_in">
    <span>USA</span>
  </div>
</div>
</div>
<div class="row">
<div class="row_in">
  <div class="row_in_in">
    <span>UK</span>
  </div>
</div>
</div>
<div class="row">
<div class="row_in">
  <div class="row_in_in">
    <span>France</span>
  </div>
</div>
</div>