Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check div is last child from parent div

In Jquery or JavaScript have a function like .hasNext(). I have the code:

function showArrowClick() {
   var activeContact = $('.contact.white_bg');
   activeContact.removeClass('white_bg');
   activeContact.next().addClass('white_bg');
}

and parent div is

<div class="list">
     <div class="contact white_bg all_contacts">All</div>
     <div class="contact">Contact1</div>
     <div class="contact">Contact2</div>
</div>

After click last div need to do something. How can I do it?

like image 590
Ulug'bek Avatar asked Mar 06 '13 10:03

Ulug'bek


4 Answers

You'll probably want :last-child.

$('a').click(function() {

  $('.list .contact:last-child').doSomething();

});

Edit:

Or if you meant clicking the last child itself...

$('.list .contact:last-child').click(function() {

  $(this).doSomething();

});
like image 156
Matt Fletcher Avatar answered Oct 04 '22 11:10

Matt Fletcher


You should verify if there is any element when you're trying to select it:

function showArrowClick() {   
   var activeContact = $('.contact.white_bg');

   if(activeContact.next('div.contact').length > 0) {
     activeContact.removeClass('white_bg');
     activeContact.next().addClass('white_bg');
   }
}
like image 23
Mihai Matei Avatar answered Oct 04 '22 11:10

Mihai Matei


Try Something Like

$('.list').find("div.contact:last").addClass('white_bg');

Second

$('.list .contact:last-child').addClass('white_bg');
like image 36
Dipesh Parmar Avatar answered Oct 04 '22 11:10

Dipesh Parmar


Have you looked at $.fn.nextAll()?

like image 27
whitneyit Avatar answered Oct 04 '22 12:10

whitneyit