How to check div - last of parent div

There is a type function in jQuery or JavaScript.hasNext() . I have a code:

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

and parent div

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

After clicking the last div, you need to do something . How can i do this?

+5
source share
7 answers

You should check if there is any element when selecting it:

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

   if(activeContact.next('div.contact').length > 0) {
     activeContact.removeClass('white_bg');
     activeContact.next().addClass('white_bg');
   }
}
+1
source

You probably want to :last-child.

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

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

});

Edit:

Or if you meant the click of the last child itself ...

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

  $(this).doSomething();

});
+2
source

.next() . . .length, , - DOM.

alert($('div.contact').next().length);
+1

-

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

$('.list .contact:last-child').addClass('white_bg');
+1

Use last-child selector

$(".list div:last-child").on('click', function(){
//Do something
});
+1
source
function showArrowClick() {
   var activeContact = $('.contact.white_bg');
   var index = activeContact.index();
   if (index === $(".contact.white_bg").children().length - 1) {
     // Current seleceted is the last div
    }
   activeContact.removeClass('white_bg');
   activeContact.next().addClass('white_bg');
}  
+1
source

All Articles