0

I try to get the path(shortest way) from one Element to another. I will never know which elements will be clicked in the DOM.

I can get the Path in the DOM for each element like in this question answered: "Get unique selector of element in Jquery" . But how can navigate from Element a to b without going the DOM back to the start( < html > ) and from there to element b?

Look at http://jsfiddle.net/VBVSE/. I get there one selector for Element A and one for B. Both have "html>body>div>div>" in common. So I want now only a selctor thats brings me in the shortest way from A to B.

HTML:

<div>
    <div>
    <div>
        <div id="eA">ElementA</div>
    </div>
    <div>
        <div>SomeOtherElement</div>
    </div>
    <div>
        <div>
            <div>
                <div>SomeOtherElement</div>
                <div id="eB">ElementB</div>
            </div>
        </div>
    </div>
</div>
</div>

<span style="font-weight:bold;">ElementAPath:</span><div id="eAp"></div>
<span style="font-weight:bold;">ElementAPath:</span><div id="eBp"></div>

jQuery (from a answer of the question link above):

jQuery.fn.extend({
getPath: function () {
    var path, node = this;
    while (node.length) {
        var realNode = node[0], name = realNode.localName;
        if (!name) break;
        name = name.toLowerCase();

        var parent = node.parent();

        var sameTagSiblings = parent.children(name);
        if (sameTagSiblings.length > 1) { 
            allSiblings = parent.children();
            var index = allSiblings.index(realNode) + 1;
            if (index > 1) {
                name += ':nth-child(' + index + ')';
            }
        }

        path = name + (path ? '>' + path : '');
        node = parent;
    }

    return path;
}
});
jQuery('#eAp').text(jQuery('#eA').getPath());
jQuery('#eBp').text(jQuery('#eB').getPath());
Community
  • 1
  • 1
basis
  • 158
  • 2
  • 8

0 Answers0