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

1

4 Answers 4

25

You could use the "attributeContains" selector:

if($("#yourTable td:last-child[id*='34a']").length > 0) { 
   //Exists, do something...
} 
3
  • 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"); Mar 13, 2009 at 0:45
  • ^ insert $ at beginning of expression Mar 13, 2009 at 0:46
  • The > 0 portion is redundant. Just element.length will work. Apr 8, 2016 at 0:41
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

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>
2

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

if ($('#myTable td:last[id*=34a]').length) {
    ...
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.