0

Preferably in Javascript. [Maybe] iterate through all the nodes and console.log() its XPath.

I searched enough and could not find an answer.

Why I need it?

I want to see the coordinates(getBoundingClientRect()) of all leaf nodes of a DOM (means, elements of an HTML).

Vishal Gupta
  • 805
  • 14
  • 15

1 Answers1

2

A combination of How to loop through ALL DOM elements on a page and how do I get the XPath of an element in an X/HTML file

should do:

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]));
}

The updated version works much better than the first installment.

wp78de
  • 18,207
  • 7
  • 43
  • 71