0

I want to show only 4 item and hide other items. how i can do it

$(".item").each(function(i, e){
      if(i == 4 ){
          $(this).addClass("hide");
      }
  })
5
  • witch four do you wanna show and witch ones not? Commented Feb 25, 2020 at 14:37
  • Is 4 a constant value for what you want to do? Is it fourth item and below that you want to hide? When do you want to show them again? Commented Feb 25, 2020 at 14:40
  • i want to hide menu items after 4. item Commented Feb 25, 2020 at 14:42
  • 2
    In pure jQuery you would do $('.item').slice(3).addClass('hide') or use :gt() inside the query; you could use .hide() as well, unless the hide class does something else Commented Feb 25, 2020 at 14:43
  • thanks @Ja͢ck it worked Commented Feb 25, 2020 at 14:48

2 Answers 2

2

As per syntax, if you write i == 4 only at 4th loop it will hide. you have to write i > 3 because array starts from zero(0), which will hide all after 4 items

$(".item").each(function(i, e){
      if(i > 3){ 
         $(this).addClass("hide");
      }
})

Or simply you can do this:

$('.item').slice(3).addClass('hide')
Sign up to request clarification or add additional context in comments.

Comments

0

You don't say if you want to show only the first four, or a particular four, but your code attempt suggests the former.

In which case, you don't need JavaScript at all - you can do it from CSS.

.item:nth-of-type(4) ~ .item { display: none; }

If for some reason you wish to do it with JS nonetheless, you could do:

$('.item:nth-child(4)').nextAll('.item').hide();

1 Comment

You're welcome. That is what happens.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.