JSFiddle - React, Tailwind, and code Playground
by David Thomas
HTML
<div>something.</div>
<div>something else</div>
<div> <a> something. </a>
<a id="demo"> ELEMENT </a>
</div>
CSS
body::before {
display: block;
content:'Route to "Example" element: " attr(data-routeto);
color: #999;
}
JavaScript
function findIndexOfLike(node) {
var children = Array.prototype.filter.call(node.parentNode.children, function (child) {
return node.tagName === child.tagName;
});
return children.indexOf(node);
}
function createIndexedPathTo(node) {
var path = [],
current = node;
while (current.tagName.toLowerCase() !== 'body') {
path.push(current.tagName.toLowerCase() + '[' + findIndexOfLike(current) + ']');
current = current.parentNode;
}
path.push('body[0]');
return path.reverse().join('/');
}
var route = createIndexedPathTo(document.querySelector('a:nth-child(2)'));
document.body.dataset.routeto = route;
console.log(route);