I have an HTML document, and it is structured thusly:
<div id="oa2">
Content
<div>
Content
<div>
. . .
</div>
</div>
</div>
And the chain of elements may go arbitrarily deep. When there is a click on the screen, I pick it up and attempt to get the parental chain of custody for the clicked element using the following JavaScript:
let a=document.getElementById("oa2");
let c=[];
let d=[];
let i=[0,0,0,0];
document.onclick=function(e){
let b=e.target;
while(b){
let f=b.childNodes;
if(b==(a||document.body)){break;};
if(!d.includes(b.id)){d[i[0]]=b.id;i[0]++;};
while(i[3]<f.length){
if(f[i[3]].nodeType==Node.TEXT_NODE)
{c[i[1]]=[];c[i[1]][i[3]]=f[i[3]].nodeValue};
i[3]++;
};
b=b.parentElement;
};
i[1]++;
i[3]=0;
};
To be clear, what I want is an array (c) which contains arrays which contain the "path" of a child element's content and the content of each successive parent element's content. Every time there is a click on the document, I want a new child array in c holding the "path" of the clicked element, with out duplicates (I took care of that with d)..
You can have a while loop that checks the parent element of the target every iteration, and get an array of the path.
document.onclick = e => {
let element = e.target
const path = []
while(element) {
path.push(element)
element = element.parentElement
}
console.log(path)
}
You can also check the event path property on Chrome and Firefox ( Safari has it too but it's something different
https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath