admin管理员组

文章数量:1318991

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?

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?

Share Improve this question asked Feb 7, 2013 at 23:33 AthapaliAthapali 1,0894 gold badges25 silver badges48 bronze badges 1
  • You could look at stackoverflow./questions/5115152/… – Chetter Hummin Commented Feb 7, 2013 at 23:40
Add a ment  | 

3 Answers 3

Reset to default 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!');
});

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

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";
    }
}

本文标签: javascriptchange table cell value jqueryStack Overflow