Fields
Fields

Reputation: 727

How to remove entire tr when a keyword is contained within a specific td

Inside a number of <tr>'s in my document there are 7 classes, each one sometimes has a corresponding class name (i.e. sub, id, assigned, sub, sub, status, and one classless "td"). Within the td class = "status" lies a span class defined as either <span class = "statusBox">Passed</span> or <span class = "statusBox">Failed</span>.

If the text contained within the span class is "Passed", I need to delete the entire <tr>. If it's failed it stays on the document. How can I achieve this?

My first attempt was through a call such as:

function() {
    if ($('tr td span.statusBox').html() == "Passed"){
    $('tr td span.statusBox').hide();  
}

But this removed every instance of only the phrase "Passed", not the entire <tr>.

I've also tried $("tr td span.statusBox:contains('Passed')").each(function(){ $(this).css("visibility","hidden"); });

I feel like this is more along the right path, but I can't seem to get it to work.

Upvotes: 3

Views: 127

Answers (3)

colestrode
colestrode

Reputation: 10658

You were close: find the status box with the word 'Passed' and then find the closest ancestor tr element and remove it from the DOM:

$("tr td span.statusBox").filter(":contains('Passed')").each(function(){
    $(this).closest('tr').remove();
});

Since the :contains operator is a jQuery extension (it has been deprecated from the CSS spec), it's faster to break the selector into two parts. The first is finding all spans of class statusBox, this will look up the elements using native browser methods. Then those elements are filtered using the :contains operator (which may have a native implementation or may be implemented in jQuery, depending on the browser).

Upvotes: 5

mkutyba
mkutyba

Reputation: 1427

$(".statusBox").each(function (i, e) {
    if ($(e).text() == "Passed") {
        $(e).closest('tr').hide();
    }
});

http://jsfiddle.net/B7Wqy/

Upvotes: 0

techfoobar
techfoobar

Reputation: 66673

It is because you are altering the visibility of the span instead of the parent <tr>. You can use $(this).closest('tr') to get to the row element and then alter its visibility.

$("tr td span.statusBox:contains('Passed')").each(function(){
    $(this).closest('tr').css("visibility","hidden"); 
});

Upvotes: 0

Related Questions