JSFiddle - React, Tailwind, and code Playground
HTML
<body>
<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>
<span>You Can see that both have got "html>body>div>div>"</span>
</body>
JavaScript
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());