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>

 

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s