3

i am new to jQuery.

i have list element as follows.

<ul>
    <li>
        <a href="abc">ABC</a>
    </li>
    <li> <!-- I want to remove this element-->
        <ul>
            <li>
                <a href="def">DEF</a>
            </li>
            <li>
                <a href="ghi">GHI</a>
            </li>
        </ul>
    </li>
</ul>

i want to remove LI element (commented in above sample) which has GHI anchor tag using jQuery. or in other ways i want to remove that element based on the href property or text contained in the anchor tag.

Please help

4 Answers 4

3
$("ul:first > li:eq(1)").remove()

Select the first ul, then remove the second li child.

Or if you meant the li with GHI tag,

$("ul:eq(1) > li:eq(1)").remove()

Select the second ul, and find the second li child.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but it will not always be the case. i want to remove the element based on the text in anchor tag or href attribute of anchor tag.
@PrateekDeshpande: Based on this comment, I have added my answer - it removes <li> element containing anchor with href equal to "ghi".
2

To remove li element placed somewhere above the anchor with href="ghi" you could do something like this:

jQuery('a[href="ghi"]').parents('ul > li').remove();

or if li element that needs to be removed is not the direct child of the ul element (good point, mrtsherman):

jQuery('a[href="ghi"]').parents('ul li').remove();

See it in action: jsfiddle.net/tadeck/EmZ4N/

2 Comments

I like this one the best. Most of the other answers provided are just wrong. There is the assumption that li being removed is a direct child of the ul, but OP didn't specify alternate cases.
@mrtsherman: Thanks, I have added the case when li we want to remove is not the direct child of ul.
1

If you want to remove li with certain href(s):

$('li > a[href^="abc"]').remove();

That is selecting all list items that contain anchors with hrefs that begin with "abc" and then removing them.

Comments

1
$('a[href="ghi"]').closest('li').closest('li').remove();

Comments

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.