Amy Neville
Amy Neville

Reputation: 10601

Remove Items From End Of Container With JQuery

I have a feed of items coming into a list using the prepend method. I've been searching but can't find a method to remove X number of items from the end - to prevent it overflowing.

How do I remove the last 3 elements from this list using jquery?

<div id="feed">
<ul>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
</ul>
</div>

Upvotes: 4

Views: 60

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 240948

You could use the .slice() method to remove the last three elements from the jQuery object:

$('#feed li').slice(-3).remove();

Snippet:

$('#feed li').slice(-3).remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="feed">
  <ul>
    <li class="item">1</li>
    <li class="item">2</li>
    <li class="item">3</li>
    <li class="item">4</li>
    <li class="item">5</li>
    <li class="item">6</li>
  </ul>
</div>


Alternatively, you could also use the jQuery :gt() selector and specify a negative number for the index. Keep in mind that the index for this selector is zero-based, which means that -4 would be used to remove the last three elements.

$('#feed li:gt(-4)').remove();

Snippet:

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

Upvotes: 4

Related Questions