Jitender
Jitender

Reputation: 7969

if statement in .eq() in jquery

I want to remove li which index in less than five. So I am using .eq(). I Know it can be done using if statement but I want to use if statement in inside eq().

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


$('li').each(function (i) {
    $(this).eq(function () {
        if (i < 5)
            return i;
        else
            return false;
    }).remove();
});

Upvotes: 2

Views: 760

Answers (3)

Ja͢ck
Ja͢ck

Reputation: 173642

Besides using :lt() selector, you can also use .slice():

$('ul').children().slice(0, 4).remove();

Upvotes: 0

Adil
Adil

Reputation: 148150

You can use lt() (less than) to get the elements with index less then give value.

Live Demo

$('li:lt(5)').remove()

Description: Select all elements at an index less than index within the matched set, reference.

The index-related selectors (including this "less than" selector) filter the set of elements that have matched the expressions that precede them. They narrow the set down based on the order of the elements within this matched set, jQuery doc.

Upvotes: 5

Satpal
Satpal

Reputation: 133423

You can use :lt() Selector

$('li:lt(5)').remove()

Upvotes: 0

Related Questions