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.

Member Avatar for stbuchok

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?

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.

Member Avatar for stbuchok

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.

Member Avatar for stbuchok

oops

Just realized that is the opposite of what you want. Give me a few minutes.

Member Avatar for stbuchok
var length = ($('ul li').length() - 2);

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

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.

Member Avatar for stbuchok

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.