获取HTML / DOM的所有元素的XPATH

时间:2018-07-12 09:01:32

标签: javascript html html5 dom xpath

最好使用Javascript。 [也许]遍历所有节点并console.log()遍历其XPath

我进行了足够的搜索,找不到答案。

我为什么需要它?

我想查看DOM所有叶子节点(即HTML的元素)的c oordinates(getBoundingClientRect())

1 个答案:

答案 0 :(得分:1)

How to loop through ALL DOM elements on a pagehow do I get the XPath of an element in an X/HTML file的组合

应该这样做:

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;

}

var all = document.getElementsByTagName("*");
for (var i=0, max=all.length; i < max; i++) {
    console.log(getXPath(all[i]));
}

更新后的版本比第一期更好。