user1658080 user1658080 - 5 months ago 19
jQuery Question

TD :contains String but not within a span Element

I want to check wether a TD contains a certain string but only if that string is NOT within a SPAN.

Let's say I want to check all TDs for "TREASURE":

<td> TREASURE <span>Water</span> </td> -> YES
<td> Water <span>TREASURE</span> </td> -> NO
<td> TREASURE </td> -> YES
<td> <div>TREASURE</div> <span>Water</span> </td> -> YES


So far I have tried different things to exclude span elements from the search but I wasn't successful.

$('table tr td:Contains("TREASURE")').not('span').each(function() {
$(this).addClass('found');
});


Thanks a lot! :)

EDIT:

Additionally the following case should also work:

<td> TREASURE <span>TREASURE</span> </td> -> YES

Answer

You can use :not() pseudo-class selector (or not() method) with :has() pseudo-class selector.

$('table tr td:contains(TREASURE):not(:has(span:contains(TREASURE)))').addClass('found');

// or

$('table tr td:contains(TREASURE)').not(':has(span:contains(TREASURE))').addClass('found');
.found {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tr>
    <td>TREASURE <span>Water</span> 
    </td>
    <td>Water <span>TREASURE</span> 
    </td>
    <td>TREASURE</td>
    <td>
      <div>TREASURE</div> <span>Water</span> 
    </td>
  </tr>
</table>

UPDATE : If the text contains in both place then use filter() method. What actually doing here is cloning the td and removing span elements from cloned object after applying the :contains selector.

$('table tr td').filter(function() {
  return $(this)
    .clone() // clone the element
    .find('span') // get all span inside cloned element
    .remove() // remove the spans
    .end() // back to cloned element
    .is(':contains(TREASURE)'); // check the cloned element contains text
}).addClass('found');
.found {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tr>
    <td>TREASURE <span>Water</span> 
    </td>
    <td>Water <span>TREASURE</span> 
    </td>
    <td>TREASURE</td>
    <td>
      <div>TREASURE</div> <span>Water</span> 
    </td>
    <td>
      <td>TREASURE <span>TREASURE</span>
      </td>
  </tr>
</table>

Comments