How to add a particular class in last div using jQuery

Most of the time I need to add class last to my last div to have another styling for the last div.

 

like –

 

<div class=”myarticle”></div>

<div class=”myarticle”></div>

<div class=”myarticle”></div>

<div class=”myarticle”></div>

<div class=”myarticle”></div>

 

While this is good if all these divs being created dynamically, but to have different styling for the last div, let say like this is the require structure we like to have on our page –

 

<div class=”myarticle”></div>

<div class=”myarticle”></div>

<div class=”myarticle”></div>

<div class=”myarticle”></div>

<div class=”myarticle lastdiv”></div>

 

To add the last in our last div we use jQuery .addClass() method.

 

Usage – jQuery(‘div.myarticle:last-child’).addClass(‘lastdiv’);

 

This single line jquery adds lastdiv class to our last div.

 

Final output –

 

<div class=”myarticle”></div>

<div class=”myarticle”></div>

<div class=”myarticle”></div>

<div class=”myarticle”></div>

<div class=”myarticle lastdiv”></div>