Hello, there is an array of the list

<ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> 

How can jquery cut the number of "li" list items to 3x?

    1 answer 1

     var elements = $("ul li:lt(3)"); $('ul').html(elements); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> 

    lt - selects all items with an index less than index among the already selected items.

     jQuery(':lt(index)') 

    index - The index of the element, starting with zero.


    Another option is to cut through slice and then push the result back into ul

     var sliceCount = 3; var els = $('ul li').slice(0, sliceCount); $('ul').html(els); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> 


    The easiest option:

     $('ul li:gt(2)').remove(); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> 

    gt - Filters a set of selected items, leaving only those whose index exceeds n. Remember that indexing starts at 0.

    • $('ul li:gt(2)').remove(); So you do not touch existing elements, but only remove unnecessary. So do not break event handlers, data that can be tied to the remaining elements. - AndryG
    • @AndryG Anywhere in the question is written about handlers? - Alexey Shimansky
    • The sample code is clearly "academic." I pointed out to future readers how dangerous the re-creation of the remaining elements is. - AndryG
    • @AndryG can add an answer, if you want) Or even add one more - Alexey Shimansky