Putting a border around the selected list item I have an HTML list. The goal is that:


When an li is clicked, the .my-list--selected class will be applied. And, since the inner div also has a border-bottom, the .border-bottom class must be removed (or else it appears as though there is a 2px wide border along the bottom if both classes are applied).
When another li is clicked, the previously selected li's .my-list--selected is removed and the .border-bottom class is reinstated (there can only be 1 '.my-list--selected' at a time).


I've written the below code and it works, but it seems really messy and overly complicated to me.

Is there a better way to go about achieving this goal?



$("li").click(function() {
  //Remove the my-list--selected class from any elements that already have it
  $('.my-list--selected').removeClass('my-list--selected');
  //Add the .border-bottom class back to any element that is missing it
  $('.my-list--selected').addClass('border-bottom');
  //Add the my-list--selected class to the clicked element
  $(this).addClass('my-list--selected');
  //Remove the border-bottom class from the clicked element
  $(this).find('.border-bottom').removeClass('border-bottom');
});
li div {
  padding: 0 10px;
}

.border-bottom {
  border-bottom: 1px solid #ccc;
}

.my-list--selected {
  border: 1px solid #ccc;
}
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;
&lt;ul&gt;
  &lt;li&gt;
    &lt;div class="border-bottom"&gt;Content&lt;/div&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;div class="border-bottom"&gt;Content&lt;/div&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;div class="border-bottom"&gt;Content&lt;/div&gt;
  &lt;/li&gt;
&lt;/ul&gt;
Are you required to have the .border-bottom class on the div elements?  I'd move those up to the li elements so you don't have to bother with the add/remove .border-bottom and you could use first-child to cleanly add a top border for the selected element if it's first (and avoid a double border for the other items).  See below snippet with the changes.



$("li").click(function() {
  //Remove the my-list--selected class from any elements that already have it
  $('.my-list--selected').removeClass('my-list--selected');
  //Add the my-list--selected class to the clicked element
  $(this).addClass('my-list--selected');
});
.border-bottom {
  border-bottom: 1px solid #ccc;
}

.my-list--selected {
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
}

.my-list--selected:first-child {
  border-top: 1px solid #ccc;
}
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;
&lt;ul&gt;
  &lt;li class="border-bottom"&gt;
    &lt;div&gt;Content&lt;/div&gt;
  &lt;/li&gt;
  &lt;li class="border-bottom"&gt;
    &lt;div&gt;Content&lt;/div&gt;
  &lt;/li&gt;
  &lt;li class="border-bottom"&gt;
    &lt;div&gt;Content&lt;/div&gt;
  &lt;/li&gt;
&lt;/ul&gt;