Home > Blockchain >  Javascript get last element from nested divs
Javascript get last element from nested divs

Time:05-18

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?

CodePudding user response:

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>

CodePudding user response:

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>

  • Related