Control Freak
Control Freak

Reputation: 13243

How to .remove() by count

Here is the HTML:

<div class="line"></div>
<div class="line"></div>
<div class="line"></div>
<div class="line"></div>

Here is the Jquery:

 if ( $( ".line" ).length > 2 ) { 
  //remove all other div.lines but keep the first 2
 }

How do you do this?

Upvotes: 1

Views: 95

Answers (4)

silly
silly

Reputation: 7887

$('.line:gt(1)').remove();

or

$('.line').each(function(pos) {
    if(pos > 1) {
        $(this).remove();
    }
});

Upvotes: 1

dfsq
dfsq

Reputation: 193311

Combine with old good plain javascript:

$(".line").slice(2).remove();​

http://jsfiddle.net/qwQWV/

Or you can use only jQuery:

$(".line").filter(':gt(1)').remove();​​​

Upvotes: 1

Chuck Norris
Chuck Norris

Reputation: 15200

$(".line:gt(1)").remove();

You can use Jquery's gt selector. This select that indexes which are greater than 1.
See jsfiddle http://jsfiddle.net/X7a4Z/1/.

Upvotes: 3

kichik
kichik

Reputation: 34744

You can use the slice() function for that. It returns parts of an array.

$(".line").slice(0, 2);

Upvotes: 1

Related Questions