Search code examples
javascriptjqueryloopseachshow-hide

JQuery loop hide items


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");
      }
  })

Solution

  • 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')