Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery remove list item where .text() = 'blabla'

Tags:

jquery

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'?

like image 683
Hailwood Avatar asked Sep 14 '10 23:09

Hailwood


2 Answers

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();
like image 115
Nick Craver Avatar answered Nov 16 '22 02:11

Nick Craver


$('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.

like image 38
alex Avatar answered Nov 16 '22 00:11

alex