2

I have one list, so I when I click on the button it should hide all li but not that li who has class name "matter" so how to do this using jquery by using only the class name.

<ul class="sub-menu">        
  <li >list 1</li>
  <li class="matter">list 2</li>
  <li >list 3</li>
  <li >list 4</li>
</ul>
<button name="btn" class="btn_click">Click me</button>
$(".btn_click").on('click', function() { 

// here code that will hide all li but not that li who has class name 'matter'
});
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Anonymous
  • 1,074
  • 3
  • 13
  • 37

2 Answers2

2

You could simply use the jQuery selector :not, or the jQuery method .not() like :

$('.sub-menu li:not(.matter)').hide();
//Or
$('.sub-menu li').not('.matter').hide();

$(".btn_click").on('click', function() {
  $('.sub-menu li:not(.matter)').hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul class="sub-menu">
  <li>list 1</li>
  <li class="matter">list 2</li>
  <li>list 3</li>
  <li>list 4</li>
</ul>

<button name="btn" class="btn_click">Click me</button>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
0

This is a pretty simple concept. Get a reference to all the li $(".sub-menu").find('li') then exclude the one .not(".matter") you do not need and hide the rest.

$(".btn_click").on('click', function() {
  $(".sub-menu").find('li').not(".matter").hide();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="sub-menu">
  <li>list 1</li>
  <li class="matter">list 2</li>
  <li>list 3</li>
  <li>list 4</li>
</ul>
<button name="btn" class="btn_click">Click me</button>

As for why I choose to not use :not() here, I just find this easier to read and maintain.

As for the $(".sub-menu").find('li') choice https://stackoverflow.com/a/16423239/125981

Alternative use the .filter()

$(".sub-menu").find('li').filter(":not(.matter)").hide();
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100