Clinton Green Clinton Green - 5 months ago 184x
Javascript Question

jQuery - Find closest sibling to list item - next or previous

I have a function that removes an li with an active class on a button click. When the active li is removed I need to transfer the active class to the closest li. Both .next and .prev work great but do not take into account if I am removing the first or last li. In this case either .next or .prev will not work.

Is there another function I can use here besides using an if statement? Unfortunately, closest did not work for me.


<li class="active">List item #1</li>
<li>List item #2</li>
<li>List item #3</li>
<li>List item #4</li>
<li>List item #5</li>


$('.conversations-wrap').on('click', '.delete-message', function(){

// delete sidebar element

// change sidebar active



you can try this

$(document).on('click', '.delete-message', function(){
  //add a fake class to the li you need to remove
  $('ul >').addClass('toDelete');
  //check if the active li is the last one in the list or not
  //if it is a last one add the class active to previous li
  if($('ul > li.toDelete').index() == $('ul > li').length - 1){
    $('ul > li.toDelete').prev('li').addClass('active');
  }else{ // if not the last add the class active to the next li
    $('ul > li.toDelete').next('li').addClass('active');
  // remove sidebar element
  $('ul > li.toDelete').remove();
  color : red;
<script src=""></script>
<li>List item #1</li>
<li>List item #2</li>
<li>List item #3</li>
<li>List item #4</li>
<li class="active">List item #5</li>

<button class="delete-message">Delete Active li</button>

Note: be sure to make all actions before you remove the item