I have a <ul>
element. How can remove all the <li>
elements inside it, except for the first and the last, using jQuery?
To remove all li elements from a ul element with JavaScript, we can set the innerHTML property of the ul element to an empty string. Then we write: document. getElementById("root").
The HTML <li> element is used to represent an item in a list. It must be contained in a parent element: an ordered list ( <ol> ), an unordered list ( <ul> ), or a menu ( <menu> ). So yes, you need to nest any <li> element inside a list or menu. However a <li> element may contain nearly every other element inside.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With