bilal
bilal

Reputation: 658

Get the last child of parent div

How can I get the last child of parent div, every time I press enter a new div created, I want to get the last div of specific parent div.

<div id="parentdiv">
    <div id="child1"></div>
    <div id="child2"></div>
    <div id="child3"></div>
</div>

Upvotes: 1

Views: 2299

Answers (3)

Ibrahim Khan
Ibrahim Khan

Reputation: 20740

You can use jQuery last() method like following.

$('#parentdiv > div').last()

UPDATE: last div of parent div having a class myclass.

$('#parentdiv > div.myclass').last()

Upvotes: 1

jforjs
jforjs

Reputation: 473

My suggestion is not to use jQuery here, as querySelector in javascript is sufficient to do your job.

var parentDiv = document.getElementById('parentdiv');

console.log(parentDiv.querySelector(':last-child'))

Upvotes: 0

Ashok kumar
Ashok kumar

Reputation: 542

$("#parentdiv :last-child");

You should use last child selector https://api.jquery.com/last-child-selector/

Upvotes: 3

Related Questions