$('.size_options li').click(function() { $('.size_options li').removeClass('active-size'); $(this).addClass('active-size'); }) 
 <ul class="size_options"> <li>123</li> <li>321</li> <li class="active-size">222</li> </ul> 

Reported as a duplicate by Peter Samokhin , Grundy javascript May 10 '18 at 9:12 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • codepen.io/anon/pen/mLxVWL mb is more convenient for someone here - Dmitry
  • You do not want to try it yourself? In this code, only when you click on an element (found by a simple selector), it removes one class and adds another. If this is a training task, it will be more useful for you to find information on how to do it without jQuery, and when you are able to do everything manually, you can use jQuery just to speed up the work. Taking the copied code from somewhere is not always good. - Peter Samokhin

1 answer 1

Elements can be selected by functions:

Hang events via addEventListener

Manage the list of element classes via Element.classList

 let list = document.querySelectorAll('.size_options'); list.forEach(ul => ul.addEventListener('click', ev => { if (ev.target.tagName !== 'LI') return; ul.querySelectorAll('li').forEach(li => { li.classList.remove('active-size'); }); ev.target.classList.add('active-size'); })) 
 .active-size { font-weight: bold; } 
 <ul class="size_options"> <li>123</li> <li>321</li> <li class="active-size">222</li> </ul> 

  • Is it possible without switch functions? - Dmitriy
  • It is impossible. The answer is not in the code, but in the links to native functions. Arrow functions in an elementary way correspond to the usual ones. You can handle it. - vp_arth
  • Okay, thank you very much - Dmitriy