如何使用JavaScript获取DOM中元素的xpath?

问题描述 投票:2回答:1

我有一个HTML页面,我希望用户能够在其中单击段落,然后使用后端API保存这些元素的xpath。

到目前为止,我能够获取该元素,但无法获取其xpath。请帮助。

javascript dom
1个回答
1
投票

我使用以下代码,对我来说很好用。有人告诉我,此功能来自Firebug的代码库。您需要将DOM元素传递给它。可以在https://codepen.io/v08i/pen/eYNONXK

上看到一个工作示例
      function getElementTreeXPath(element) {
        if (element && element.id) {
          return '//*[@id="' + element.id + '"]';
        }
        var paths = [];  // Use nodeName (instead of localName) 
      // so namespace prefix is included (if any).
      for (; element && element.nodeType == Node.ELEMENT_NODE; 
             element = element.parentNode)
      {
          var index = 0;
          var hasFollowingSiblings = false;
          for (var sibling = element.previousSibling; sibling; 
                sibling = sibling.previousSibling)
          {
              // Ignore document type declaration.
              if (sibling.nodeType == Node.DOCUMENT_TYPE_NODE)
                  continue;

              if (sibling.nodeName == element.nodeName)
                  ++index;
          }

          for (var sibling = element.nextSibling; 
              sibling && !hasFollowingSiblings;
              sibling = sibling.nextSibling)
          {
              if (sibling.nodeName == element.nodeName)
                  hasFollowingSiblings = true;
          }

          var tagName = (element.prefix ? element.prefix + ":" : "") 
                            + element.localName;
          var pathIndex = (index || hasFollowingSiblings ? "[" 
                     + (index + 1) + "]" : "");
          paths.splice(0, 0, tagName + pathIndex);
      }
        return paths.length ? "/" + paths.join("/") : null;
      }


function xpath(element) {
  console.log(getElementTreeXPath(element));
}
© www.soinside.com 2019 - 2024. All rights reserved.