2

I need to find a table cell that contains certain text value and change that to something else.

    <table><tr>
<td>You are nice</td>
<td>I hate you</td>
</tr></table>

Find the table cell that contains "I hate you" and change that to "I love you".

How do I do that in Jquery?

Athapali
  • 1,091
  • 4
  • 25
  • 48

3 Answers3

4

Using :contains selector:

$('td:contains("I hate you")').text('....');

Using filter method:

$('td').filter(function(){
   // contains
   return $(this).text().indexOf("I hate you") > -1;
   // exact match
   // return $(this).text() === "I hate you";
}).text('...');

Or:

$('td').text(function(i, text){
   return text.replace('I hate you', 'I love you!');
});
Ram
  • 143,282
  • 16
  • 168
  • 197
2

A simple contains selector should do the trick followed by setting the text value

$("td:contains('I hate you')").text('I love you');

contains selector ref

Chris Moutray
  • 18,029
  • 7
  • 45
  • 66
  • Works good but note this would also select td's containing the text "I hate you all" etcetera... (not exact match) – jtheman Feb 07 '13 at 23:42
  • @jtheman lol you did use the term *contains* in your question :) but out of interest what's the thinking behind this? There's a code smell here when your looking to swap a text value rather than explicit matching on table cells by id for example... – Chris Moutray Feb 08 '13 at 10:33
0

Use querySelectorAll("td"), iterate over all returned elements and check the textNode's value.

var tds = document.querySelectorAll("td");
for (var i = 0; i < tds.length; i++) {
    if (tds[i].firstChild.nodeValue == "I hate you"){
        tds[i].firstChild.nodeValue = "I love you";
    }
}
DYN
  • 36
  • 3