Search code examples
javascriptjquery-selectors

How to get last child from parent element using query selector method?


For example:

<div class="list-container">
  <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.


Solution

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

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

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