0

What would be the quickest way to go through all of the list items in one unordered list and remove all of the items after a specified list item?

Example: Let's say the list will always contain an item with the text "Hobbies." The javascript bit will have to find that item and remove all of the li items after it.

3 Answers 3

1

Using :contains and .nextAll:

$('li:contains("Hobbies.")').nextAll().hide();
Sign up to request clarification or add additional context in comments.

1 Comment

nextAll! Awesome. I'll have to research that more. Thanks.
1

Grab your item using the :contains selector to look for "Hobbies". Then you can grab all li items after it with nextAll() and remove() them.

Comments

1

This will hide all the li elements after the specific one

$('li').filter(function(index) { return $(this).text() === "Hobbies"; }).nextAll().hide();

2 Comments

Could you provide some info on contains vs. filter? Thanks!
contains will return items if the specific text is found anywhere within the text. For example 'I have Hobbies.' will be selected if you use contains. Filter gives you option to write your own function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.