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

139
Views
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 answers
Answer question

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 Report

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 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!