【问题标题】:Convert the result of string.indexOf to a reference path to a DOM element将 string.indexOf 的结果转换为 DOM 元素的引用路径
【发布时间】:2018-12-19 17:19:56
【问题描述】:

给定以下代码:

<div class="parent">
  <div class="child">3</div>
</div>

let parent = document.querySelector('.parent');
let child = parent.querySelector('.child')
let strParent = parent.outerHTML.toString()
let strChild = child.outerHTML.toString()
let indexOfChild = strParent.indexOf(strChild)

现在我在字符串化的 HTML 中有子索引,如何将其转换为 DOM 路径(xpath/css 选择器)

抱歉,如果不是 100% 清楚,英语不是我的第一语言。

【问题讨论】:

  • 我认为没有任何直接的方法可以做到这一点。你为什么不想用 DOM 本身来做呢?
  • 或许你可以关注firebug的实现stackoverflow.com/a/3454545/5842628

标签: javascript html css dom xpath


【解决方案1】:

根据您的问题猜测,应该这样做:

function getXPath(node) {
    var comp, comps = [];
    var parent = null;
    var xpath = '';
    var getPos = function(node) {
        var position = 1, curNode;
        if (node.nodeType == Node.ATTRIBUTE_NODE) {
            return null;
        }
        for (curNode = node.previousSibling; curNode; curNode = curNode.previousSibling) {
            if (curNode.nodeName == node.nodeName) {
                ++position;
            }
        }
        return position;
     }

    if (node instanceof Document) {
        return '/';
    }

    for (; node && !(node instanceof Document); node = node.nodeType == Node.ATTRIBUTE_NODE ? node.ownerElement : node.parentNode) {
        comp = comps[comps.length] = {};
        switch (node.nodeType) {
            case Node.TEXT_NODE:
                comp.name = 'text()';
                break;
            case Node.ATTRIBUTE_NODE:
                comp.name = '@' + node.nodeName;
                break;
            case Node.PROCESSING_INSTRUCTION_NODE:
                comp.name = 'processing-instruction()';
                break;
            case Node.COMMENT_NODE:
                comp.name = 'comment()';
                break;
            case Node.ELEMENT_NODE:
                comp.name = node.nodeName;
                break;
        }
        comp.position = getPos(node);
    }

    for (var i = comps.length - 1; i >= 0; i--) {
        comp = comps[i];
        xpath += '/' + comp.name;
        if (comp.position != null) {
            xpath += '[' + comp.position + ']';
        }
    }

    return xpath;

}

let parent = document.querySelector('.parent');
console.log(getXPath(parent));

let child = parent.querySelector('.child');
console.log(getXPath(child));
<div class="parent">
  <div class="child">3</div>
</div>

这将返回 parentchild 节点的 XPath。

【讨论】:

    猜你喜欢
    • 2016-09-12
    • 2010-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 2014-07-13
    • 2015-08-06
    • 2014-08-03
    相关资源
    最近更新 更多