itsututa
itsututa

Reputation: 157

Remove elements if text matches a string in jQuery

I have the following markup:

<div id="breadcrumbs">
  <ul>
   <li><span class="crumblink"><a href="/">Home</a></span></li>
   <span class="arrows"> »</span>  
   <li><span class="crumblink"><a href="/locations-brands">Publishing Regions</a></span></li>
   <span class="arrows"> »</span>  
   <li><span class="crumblink"><a href="/locations-brands/publications">Locations &amp; Brands</a></span></li>
   <span class="arrows"> »</span>
   <li><span class="crumblink"><a href="/locations-brands/publications/popupbrand">Publications</a></span></li>
   <span class="arrows"> »</span>  
  </ul>
</div>

How can I remove a <li> if has string "Publications" as well as its next span.arrows?

Upvotes: 1

Views: 3675

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074335

There are several ways to do this, but one would be to use $() with a selector to look up the lis, then loop through them (each() is handy for that) using text() to get their text, String#indexOf to check contents, and next() to see if the next thing is a relevant span (but see note below), and of course remove() to remove an element.

When selecting the lis, you can use the special :contains("text") selector jQuery adds, but note that if you do, it means jQuery can't use the browser's built-in tools for finding elements, and so there could be a performance impact.


Note that your HTML is invalid. ul elements cannot have span elements as children; the only valid immediate children of ul elements are li elements (which can have spans inside them if you like). What the browser does when you send invalid markup like that will be browser-dependent.

Upvotes: 5

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123387

try this:

$('#breadcrumbs li:contains("Publications")')  
     /* find li node containing Publications */
  .next('span').remove().end()                
     /* search next span and remove it */
  .remove();                                   
     /* end() reset last selection (made with next()), so last remove() is removing the li */

example fiddle: http://jsfiddle.net/MZysf/

Upvotes: 2

Related Questions