fishbaitfood
fishbaitfood

Reputation: 659

jQuery remove last three elements after specific element

How do I remove the last three items (which have the same class), after a specific element (p#heading)?

<p id="heading">HEADING</p>
<p class="txt"></p>
<p class="txt"></p>
<p class="txt"></p>
<p class="txt"></p>
<p class="txt"></p>
<p class="txt"></p>

Thanks already!

Upvotes: 1

Views: 372

Answers (3)

Vlad Ciobanu
Vlad Ciobanu

Reputation: 1473

You need to use the ~ selector.

$(document).ready(function() {
    var allTxt = $('#heading ~ .txt');
    var toBeRemoved = allTxt.slice(allTxt.length - 3);
    toBeRemoved.remove();
});​​

Upvotes: 0

Josh Davenport-Smith
Josh Davenport-Smith

Reputation: 5511

This matches .txt elements after p#heading and slices the selection to the last three in the matched set.

$matchedElements = $('p#heading').nextAll('.txt').slice(-3);​​

Upvotes: 2

Eli
Eli

Reputation: 14827

Try this:

$("p#heading").siblings(".txt").slice(-3).remove();

Upvotes: 2

Related Questions