tags:

views:

4765

answers:

4

Hi! 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!!!

+2  A: 

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
A: 

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
+8  A: 

You could use the "attributeContains" selector:

if($("#yourTable td:last-child[id*='34a']").length > 0) { 
   //Exists, do something...
}
CMS
And, if your "something" consists of a jQuery operation, say setting a css, you can just chain it up -- no if required: ("#yourTable td:last-child[id*='34a']").css("color", "red");
Chris Hynes
^ insert $ at beginning of expression
Chris Hynes
A: 

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