How to add class to all li, less than what was clicked

1

I want to add a class hidden to all li , but not to the li that was clicked. How can I do this using jQuery?

jQuery(".render-menu li").on('click', function() {
  alert();
  jQuery(".render-menu").not($(this)).parent().addClass('hidden');
});
.hidden {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ulclass="render-menu">
  <li class="font-size">list 1</li>
  <li class="font-size">list 2</li>
  <li class="font-size">list 3</li>
  <li class="font-size">list 4</li>
</ul>
    
asked by anonymous 21.09.2018 / 20:24

3 answers

4

You're already using jQuery.not() that does just what you need, it returns a jQuery object by removing the element passed it to the set.

var $items = $(".render-menu li");

$items.on('click', function() {
  $items.not(this).addClass('hidden');
});
.hidden {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ulclass="render-menu">
  <li class="font-size">list 1</li>
  <li class="font-size">list 2</li>
  <li class="font-size">list 3</li>
  <li class="font-size">list 4</li>
</ul>
    
21.09.2018 / 20:40
3

You can solve using the .hide() and .show() methods like this:

jQuery(".render-menu li").on('click', function() {
  $(".render-menu li").hide();
  $(this).show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ulclass="render-menu">
  <li class="font-size">list 1</li>
  <li class="font-size">list 2</li>
  <li class="font-size">list 3</li>
  <li class="font-size">list 4</li>
</ul>
          
    
21.09.2018 / 20:37
3

There is also the siblings method of jQuery that returns the siblings, that is, elements that are at the same level of the DOM as the element in question. Optionally it is possible to set a selector as parameter, siblings('li') .

$(".render-menu li").on('click', function() {
  $(this).siblings().addClass('hidden');
});
.hidden {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ulclass="render-menu">
  <li class="font-size">list 1</li>
  <li class="font-size">list 2</li>
  <li class="font-size">list 3</li>
  <li class="font-size">list 4</li>
</ul>
    
21.09.2018 / 20:51