Home > Back-end >  How to get last child from parent element using query selector method?
How to get last child from parent element using query selector method?

Time:06-25

For example:

<div >
  <p>hello<p>
  <p>hello<p>
  <p>hello<p>
  <p>hello<p>
</div>

How to get that last child element? I would like to point out that the children elements are dynamically created and keep increasing or decreasing according to the user's whim. And I want to be able to pick the last child every time this happens. That's why I ask. Plz, share me the syntax. Thank you.

CodePudding user response:

.list-container > p:last-child will do

And please, avoid bloatware, such as jquery...

console.log(document.querySelector(".list-container > p:last-child"));
<div >
  <p>hello1</p>
  <p>hello2</p>
  <p>hello3</p>
  <p>hello4</p>
</div>

  • Related