JSFiddle - React, Tailwind, and code Playground
by sandro_paganotti
HTML
<div id="root1">
<p></p><p></p><a><span></span></a>
</div>
JavaScript
var root = document.querySelector("#root1");
var target = document.querySelector('#root1 span');
function tracePath(target, root){
var steps = [], counter;
while(target !== root){
counter = 1;
while(target.previousSibling){
target = target.previousSibling;
if(target.nodeType !== 3){
counter ++;
}
}
steps.push(counter);
target = target.parentNode;
}
return steps.reverse();
}
var steps = tracePath(target, root);
console.log(document.querySelector('#root1 *:nth-child(' + steps.join(') *:nth-child(') + ')'));