allegutta
allegutta

Reputation: 5644

jQuery: Remove all elements after the first n elements?

I have something close to this:

<div class="batman-pictures">
    <a><img /></a>
    <a><img /></a>
    <a><img /></a>
    <a><img /></a>
    <a><img /></a>
    <a><img /></a>
</div>

I don't know how many <a><img /></a> that will be generated (I am fetching them from an API), and I want to delete all elements after the first three(n) <a><img /></a>. How can I do this in jQuery?

Upvotes: 3

Views: 1119

Answers (2)

Chizzle
Chizzle

Reputation: 1715

Use nth selector. https://jsfiddle.net/j5cthunu/

$(".batman-pictures a:nth-child(n+4)").remove();

Upvotes: 0

Cl&#225;udio Barreira
Cl&#225;udio Barreira

Reputation: 459

Try this.

$(".batman-pictures a:nth-child(3)").nextAll().remove();

Upvotes: 7

Related Questions