jQuery Add/Remove class on parent/sibling

By Aryan Maurya / February 18, 2021

The jQuery siblings() method is used to get the sibling elements of the selected element.

The following example will highlight the siblings of the <li> element by adding the class .active on document ready.

HTML CODE

In the initial step, you need to load the latest version of jQuery into your file.

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<ul>
<li>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</li>
<li>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</li>
<li>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</li>
<li>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</li>
<li>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</li>
</ul>

CSS CODE

ul li{
  cursor: pointer;
  background: #008f8d;
  list-style: none;
  margin-bottom: 15px;
  padding: 7px 15px;
}

.active{
  background: black;
  color: white;
}

jQuery CODE

Finally, we will write down our jquery code.

$(document).ready(function(){
  $('li').click( function(){
    $(this).toggleClass('active').siblings().removeClass('active');
  });
});

 

May I Help You?