Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete all li except for previous five lis and next five lis

I want to delete all li within an ul except for previous five lis and next five lis.

For example:

<ul>
    <li id="Li0"></li>
    <li id="Li1"></li>
    <li id="Li2"></li>
    <li id="Li3"></li>
    <li id="Li4"></li>
    <li id="Li5"></li>
    <li id="Li6"></li>
    <li id="Li7"></li>
    <li id="Li8"></li>
    <li id="Li9"></li>
    <li id="Li10"></li>
    <li id="Li11"></li>
    <li id="Li12"></li>
    <li id="Li13"></li>
    <li id="Li14"></li>
    <li id="Li15"></li>
    <li id="Li16"></li>
    <li id="Li17"></li>
    <li id="Li18"></li>
    <li id="Li19"></li>
    <li id="Li20"></li>
</ul>

Let say I click on Li with id Li9. So the result should be

 <ul>
    <li id="Li4"></li>
    <li id="Li5"></li>
    <li id="Li6"></li>
    <li id="Li7"></li>
    <li id="Li8"></li>
    <li id="Li9"></li>
    <li id="Li10"></li>
    <li id="Li11"></li>
    <li id="Li12"></li>
    <li id="Li13"></li>
    <li id="Li14"></li>
</ul>

I know there are :lt() and :gt() selectors for excluding elements but till now I haven't made much progress.

like image 374
ankur Avatar asked Mar 14 '12 13:03

ankur


1 Answers

If you want to remove all elements except the previous and following five, relative to the clicked element, you can use .slice() [docs] together with .index() [docs]:

// assuming `this` refers to the clicked li element
var index = $(this).index(),
    $lis = $(this).parent().children();

// Math.max(...) guarantees that we are not removing from 0 to the end of
// the list of `index - 5` is negative.
// Alternatively you can use `5 > index ? 0 : index - 5`
$lis.slice(0, Math.max(0, index - 5)).add($lis.slice(index + 6)).remove();

This was the answer to the question "Remove all but the first and last five elements in a list".

That's very easy to do with .slice() [docs]:

$('ul > li').slice(5, -5).remove();
like image 152
Felix Kling Avatar answered Sep 23 '22 13:09

Felix Kling