Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
Javascript obtiene el último elemento de divs anidados

Tengo la siguiente estructura html:

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

¿Cómo puedo usar la consulta JS DOM para devolver el último elemento div marcado en la estructura anterior?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

¡Interesante! Pruébelo de esta manera (usando 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 Report

0

Puede probar algo como esto usando querySelector junto con lastElementChild . Agregué los id para que pueda ver que obtiene el elemento correcto, pero en realidad no necesita tener los id para hacer el trabajo.

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!