tags:

views:

28

answers:

3

I have the following structure

<ul>
 <li><a ...>something</a></li>
 ...
 <li><a ...>blabla</a></li>
<ul>

I need to remove the li element where the text of the anchor is blabla.

How would i go about selecting this element? $(--what selector here--)

or do I need to loop over each li and compare its .text() value to 'blabla'?

+2  A: 
$('li > a:contains("blabla")').remove();

Have a look at the :contains selector.

I've just noticed that :contains does partial matching. You may need to do...

$('li > a:contains("blabla")').each(function() {
     if ($(this).text() === 'blabla') {
         $(this).parent().remove();
     }
});

You could also make the selector less strict if doing it that way.

... or you could do it much neater like Nick Craver.

alex
These won't remove the `<li>`. They will remove the `<a>` instead.
patrick dw
@patrick Ah yes, you are correct.
alex
Since the `<a>` is the only content of the `<li>` you can just do the check on the `<li>` element's text :)
Nick Craver
+3  A: 

If you want a contains (substring match) then :contains() works:

$('li:contains("blabla")').remove();

If you want an exact match, e.g. not matching "blablabla", you can use .filter():

$('li').filter(function() { return $.text([this]) === 'blabla'; }).remove();
Nick Craver
+1  A: 

If you want to avoid removing lis containing blabla unless blabla is further nested, use this:

$("ul li > a:contains('blabla')").parent().remove();

Otherwise, the first li from this HTML will be removed even though "blabla" is not where you might be targeting it:

<ul>
    <li>
        <div>
            Some nested content here:
            <span>
                Blablabla
            </span>
        </div>
    </li>
    <li>Some text</li>
</ul>
SimpleCoder
This one also is targeting the `<a>` instead of the `<li>`.
patrick dw
Ah thank you, I have fixed it.
SimpleCoder