Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

88
Vistas
Get the nodeValues of all parent elements of element?

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)..

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda