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

138
Vistas
Javascript get last element from nested divs

I have the following html structure:

<div>
  <div>
    <div>  // 1
        <div></div>
    </div>
    <div> // 2
        <div></div>
    </div>
    ...
    <div> // n
        <div></div>
    </div> // <---- return this one
  </div>

  <div></div>
</div>

How can I use the JS DOM query to return the last div element marked in the above structure?

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

0

Interesting! Try it this way (using xpath):

result = document.evaluate(
    '(//div//div[./div])[last()]',
    document,
    null,
    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
    null
  );
  alert(result.snapshotItem(0).outerHTML);
<div>
  <div>
    <div>  // 1
        <div></div>
    </div>
    <div> // 2
        <div></div>
    </div>
    ...
    <div> // return me
        <div>child of return me </div>
    </div> // ---- return this one
  </div>

  <div></div>
</div>

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can try something like this using querySelector together with lastElementChild. I added the ids so that you can see it gets the correct element but you don't actually need to have the ids to get the job done.

let parent = document.querySelector('div > div');
console.log(parent.lastElementChild);
console.log(parent.lastElementChild.innerText);
<div>
  <div>
    <div id="first">
      <div>First Text</div>
    </div>
    <div id="second">
      <div>Second Text</div>
    </div>
    <div id="last">
      <div>Last Text</div>
    </div>
  </div>

  <div></div>
</div>

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