hansi silva
hansi silva

Reputation: 99

jQuery find td with class name and change the text based on value

I have table and i want to filter all td values based on class name and then if td holds specific text replace it with new text. below is my current code. its not working properly and updating all the td's . please advice how to proceed.

html

 <td class="actionclass">' . $page->action . '</td>

jquery

$("tbody").find("tr").each(function() { //get all rows in table
    var ratingTdText = $(this).find('td.actionclass').text();
    if ((ratingTdText == "saved block")) {
        this.innerHTML = 'changed';
    }
});

===

update

              $("tbody tr td.actionclass").each(function() {       
                var ratingTdText = $(this).text();
                console.log(ratingTdText);
                if(($(this).is(':contains("new")')) || ($(this).is(':contains("saved")'))) {
                        (this).text().replace("top", "TopBar"); 
                         (this).text().replace("left", "LeftBar"); 
                          (this).text().replace("bottom", "BottomBar"); 

                }

            });  

Upvotes: 2

Views: 26458

Answers (2)

Satpal
Satpal

Reputation: 133403

this refers to TR element not the TD, change the selector in the find() and your code will work

$("tbody").find("tr").each(function() { //get all rows in table
    var ratingTd = $(this).find('td.actionclass');//Refers to TD element
    if (ratingTd.text() == "saved block") {
        ratingTd.text('changed');
    }
});

OR

//get all td with actionclass in table
$("tbody tr td.actionclass").each(function() {       
    var ratingTdText = $(this).text();
    if (ratingTdText == "saved block") {
        this.innerHTML = 'changed';
    }
});

Your code can be improved using .filter()

//get all td with actionclass in table
$("tbody tr td.actionclass").filter(function() {       
    return $(this).text() == "saved block";
}).text('changed');

Upvotes: 6

Suresh Atta
Suresh Atta

Reputation: 121998

 this.innerHTML = 'changed';

Should be

 ratingTdText.innerHTML = 'changed';

You shouldn't use this inside because it is pointing to row not your td

Upvotes: 0

Related Questions