How to remove all li elements inside an ul except the first and the last elements using jQuery?

前端 未结 5 1454
小鲜肉
小鲜肉 2020-12-23 13:27

I have a

    element. How can remove all the
  • elements inside it, except for the first and the last, using jQuery?

5条回答
  •  生来不讨喜
    2020-12-23 14:07

    To remove from all ul-s on the page the li-s that are neither the first nor the last:

    $('ul li:not(:first-child):not(:last-child)').remove();
    

    Or using a specific id:

    $('#yourul li:not(:first-child):not(:last-child)').remove();
    

    If you have a jQuery object with your ul in it:

    $(yourul).find('li:not(:first-child):not(:last-child)').remove();
    

提交回复
热议问题