0

Given the following code:

<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)

now that I have the index of the child inside stringified HTML how can I convert that to a DOM path (xpath/css selector)

Sorry if that's not 100% clear, English is not my first language.

Jacob
  • 392
  • 2
  • 12

1 Answers1

0

Guessing from your question, this 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;

}

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>

This returns the XPath of the parent ant the child node.

wp78de
  • 16,078
  • 6
  • 34
  • 56