Display only the first 3 elements of a list (Javascript, jQuery)

Asked

Viewed 484 times

0

Some elements inside can vary according to the page. I can scroll through this UL, and treat each LI as an element of the Array. My question is how is it possible to display only the first 3 LI and hide the rest so that it is not displayed.

<ul class="minhaClasse">
<li>Elemento</li>
<li>Elemento</li>
<li>Elemento</li>
<li>Elemento</li>
<li>Elemento</li>
</ul>

My project has jQuery so making it easier is feasible tbm =) Obg guys

3 answers

1

Use the method .Slice() jQuery with value 3. Since the value is base 0, it will hide from 4th element (index 3) to last:

$(".minhaClasse li").slice(3).hide();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="minhaClasse">
   <li>Elemento</li>
   <li>Elemento</li>
   <li>Elemento</li>
   <li>Elemento</li>
   <li>Elemento</li>
   <li>Elemento</li>
   <li>Elemento</li>
</ul>

The method accepts 2 arguments: start and end. If the second is omitted, it will go to the end. Unseen elements will be left with display: none.

If you want to remove the unseen elements once and for all, simply change the .hide() for .remove():

$(".minhaClasse li").slice(3).remove();
  • 1

    I will give +1, very simple and lean.

  • 1

    Thanks! Gave +1 tb in its for being functional, although not so dry :D

1

Can traverse the li through the method each() and give a Hide() in others:

$(() => {
  $("li").each(function(index) {
    console.log(index + ": " + $(this).text());
    
    if(index > 2) {
      $(this).hide();
    }
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul class="minhaClasse">
  <li>Elemento 1</li>
  <li>Elemento 2</li>
  <li>Elemento 3</li>
  <li>Elemento 4</li>
  <li>Elemento 5</li>
</ul>

1

Face to do only with CSS using :nth-child() you can take from the 3 element and put display:none for everyone.

Here in the example I put only color:red from 4 to 6, but you can put whatever you want as display:none for example how I did 7 to 9 that do not even appear on the screen... If you are interested in seeing more about nth-child() suggest reading What do "n" means, numbers and signals on "Nth-Child" or "Nth-last-Child" selectors"?

li:nth-child(n+4) {
    /* display: none; */
    color: red;
}
li:nth-child(n+7) {
    display: none;
}
<ul>
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
    <li>item 4</li><!-- daqui para baixo fica vermelho -->
    <li>item 5</li>
    <li>item 6</li>
    <li>item 7</li><!-- daqui para baixo não aparece -->
    <li>item 8</li>
    <li>item 9</li>
</ul>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.