1

Hi I am trying to modify content in the 3rd cell of a table using jQuery if that table row contains specific string. My code is below. It doesn’t seem to work.

$(‘tr:contains(test1)’).find(‘td:nth-child(2)’).html(‘test2’);
Kay
  • 133
  • 1
  • 7
  • 1
    Your "quotes" are not vailid in any language that I know of .. It looks like you copied and pasted from a word doc .. Secondly I think `test1` should be *in* quotes : `$(tr:contains('test1')).find(td:nth-child(2)).html('test2');` [JavaScript Quotes](https://stackoverflow.com/questions/242813/when-should-i-use-double-or-single-quotes-in-javascript) – Zak Nov 05 '20 at 03:05
  • Thirdly, think about using your `console` and watch for JavaScript errors. **F12** is your friend. – Zak Nov 05 '20 at 03:11
  • @Zak I typed from my phone so the quotes are like ‘’. Anyway, I don’t think test1 needs to be within quotes but I tried that already. There is no error in console. – Kay Nov 05 '20 at 03:13
  • `nth-child` indexes are 0-based, so `nth-child(2)` will give you the 2nd child. For the 3rd child, you need `nth-child(3)`. – kmoser Nov 05 '20 at 05:19

1 Answers1

1

Alternative way to achieve above is using eq(2) it will find element which is at 2 index starting from 0.

Demo Code:

$("tr:contains(test1)").find("td:eq(2)").html("test2");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>1</td>
    <td>test1 </td>
    <td>something </td>
  </tr>
  <tr>
    <td>2</td>
    <td>test1 </td>
    <td> something</td>
  </tr>
  <tr>
    <td>3</td>
    <td>test4 </td>
    <td> something</td>
  </tr>
</table>
Swati
  • 28,069
  • 4
  • 21
  • 41