17

I have a table and I want to know if its last td its id contains a certain string. For example, if my last td has id "1234abc", I want to know if this id contains "34a". And I need to do that in a 'if' statement.

if(myLastTdId Contains "blablabla"){ do something }

Thanks!!!

André Miranda
  • 6,420
  • 20
  • 70
  • 94

4 Answers4

25

You could use the "attributeContains" selector:

if($("#yourTable td:last-child[id*='34a']").length > 0) { 
   //Exists, do something...
} 
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
12

This is easily done with indexOf and last-child.

<table id='mytable'>
<tr>
  <td id='abc'></td>
  <td id='cde'></td>
</tr>
</table>

<script>
if($('#mytable td:last-child').attr('id').indexOf('d') != -1) {
   alert('found!');
}
</script>

Here it would alert 'found' because d appears in the string cde

Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
2

If your td is "bare" (i.e. not wrapped in a jQuery object), you can access its id attribute directly:

if (myTD.id.indexOf("34a") > -1) {
    // do stuff
}

If it is in a jQuery object, you'll need to get it out first:

if (jMyTD[0].id.indexOf("34a") > -1 {
    // do stuff
}

The indexOf function finds the offset of one string within another. It returns -1 if the first string doesn't contain the second at all.

Edit:

On second thought, you may need to clarify your question. It isn't clear which of these you're trying to match "34a" against:

  • <td id="1234abcd">blahblah</td>
  • <td id="blahblah">1234abcd</td>
  • <table id="1234abcd"><tr><td>blahblah</td></tr></table>
  • <table id="blahblah"><tr><td>1234abcd</td></tr></table>
Ben Blank
  • 54,908
  • 28
  • 127
  • 156
2

Not completely clear if you mean last td in each tr, or the very last td:

if ($('#myTable td:last[id*=34a]').length) {
    ...
}
Scott Evernden
  • 39,136
  • 15
  • 78
  • 84