Note that there are some explanatory texts on larger screens.

plurals
  1. POGet path from a element to another element with jquery
    text
    copied!<p>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.</p> <p>I can get the Path in the DOM for each element like in this question answered: "<a href="https://stackoverflow.com/questions/5706837/get-unique-selector-of-element-in-jquery">Get unique selector of element in Jquery</a>" . But how can navigate from Element a to b without going the DOM back to the start( &lt; html > ) and from there to element b?</p> <p>Look at <a href="http://jsfiddle.net/VBVSE/" rel="nofollow noreferrer">http://jsfiddle.net/VBVSE/</a>. 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.</p> <p>HTML: </p> <pre><code>&lt;div&gt; &lt;div&gt; &lt;div&gt; &lt;div id="eA"&gt;ElementA&lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;div&gt;SomeOtherElement&lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;div&gt; &lt;div&gt; &lt;div&gt;SomeOtherElement&lt;/div&gt; &lt;div id="eB"&gt;ElementB&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;span style="font-weight:bold;"&gt;ElementAPath:&lt;/span&gt;&lt;div id="eAp"&gt;&lt;/div&gt; &lt;span style="font-weight:bold;"&gt;ElementAPath:&lt;/span&gt;&lt;div id="eBp"&gt;&lt;/div&gt; </code></pre> <p>jQuery (from a answer of the question link above):</p> <pre><code>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 &gt; 1) { allSiblings = parent.children(); var index = allSiblings.index(realNode) + 1; if (index &gt; 1) { name += ':nth-child(' + index + ')'; } } path = name + (path ? '&gt;' + path : ''); node = parent; } return path; } }); jQuery('#eAp').text(jQuery('#eA').getPath()); jQuery('#eBp').text(jQuery('#eB').getPath()); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload