0

Hi
I want to remove the first <LI> item and last three <LI> item from <UL> list. How to write code in JQuery.

I need the below list

<ul>
   <li>1</li>
   <li>2</li>
   <li>3</li>
   <li>4</li>
   <li>5</li>
   <li>6</li>
   <li>7</li>
</ul>

as below result

<ul>
   <li>1</li>
   <li>5</li>
   <li>6</li>
   <li>7</li>
</ul>

I tried like

$("ul li:not(:first-child, eq(-2))").remove();

but does not give the clear result to me.

2
Contributors
7
Replies
8
Views
5 Years
Discussion Span
Last Post by stbuchok
0

Your explanation of what you want says that you want to remove 1, 5, 6 and 7. However you say that your results are to keep 1, 5, 6, and 7. Can you clarify as to which you want?

0

I given :not selector which will avoid 1,5,6 and 7 was my thought. Actually many li items will be in between 1 and 5. 1, 5, 6 and 7 element is constant. So I want to remove all elements except 1, 5, 6 and 7 that means to remove all elements between 1 and 5 element.

0

You don't need to do it in all one selector:

$("ul li:first-child").remove();

for(var i = 0; i < 3; i++){
    $("ul li:last-child").remove();
}

This is easy to read and easy to understand.

0
var length = ($('ul li').length() - 2);

for(var i = 2; i < length; i++){
    $('ul li:nth-child(2)').remove();
}
0

Fine stbuchok..
Thanks for your help. But, Is there any way to achieve this without looping though the li. Any way first and last three element is constant.

0

You can try the gt and lt (great than and less than) selectors:

$('ul li:gt(0):lt(' + ($('ul li').length - 3) + ')').remove();

However this only works if the ('ul li') selector refers to one unordered list. If there are multiple unordered lists on the page this will not work.

I honestly think the best way is with the looping. It is easier to read and maintain.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.