Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - find table row containing table cell containing specific text

Tags:

jquery

dom

I need to get a tr element which contains a td element which contains specific text. The td will contain that text and only that text (so I need text = 'foo' not text contains 'foo' logic).

So I need the equivalent of the following 'pseudo jQuery':

var tableRow = $(table td[text = 'foo']).parent('tr');

Can anyone provide the correct syntax?

like image 236
David Avatar asked May 26 '11 08:05

David


4 Answers

You can use filter() to do that:

var tableRow = $("td").filter(function() {
    return $(this).text() == "foo";
}).closest("tr");
like image 53
Frédéric Hamidi Avatar answered Oct 23 '22 06:10

Frédéric Hamidi


I know this is an old post but I thought I could share an alternative [not as robust, but simpler] approach to searching for a string in a table.

$("tr:contains(needle)"); //where needle is the text you are searching for.

For example, if you are searching for the text 'box', that would be:

$("tr:contains('box')");

This would return all the elements with this text. Additional criteria could be used to narrow it down if it returns multiple elements

like image 28
pi. Avatar answered Oct 23 '22 06:10

pi.


$(function(){
    var search = 'foo';
    $("table tr td").filter(function() {
        return $(this).text() == search;
    }).parent('tr').css('color','red');
});

Will turn the text red for rows which have a cell whose text is 'foo'.

like image 17
Rezler Avatar answered Oct 23 '22 07:10

Rezler


This will search text in all the td's inside each tr and show/hide tr's based on search text

 $.each($(".table tbody").find("tr"), function () {                              

                if ($(this).text().toLowerCase().replace(/\s+/g, '').indexOf(searchText.replace(/\s+/g, '').toLowerCase()) == -1)
                    $(this).hide();
                else
                    $(this).show();
 });
like image 2
Nalan Madheswaran Avatar answered Oct 23 '22 07:10

Nalan Madheswaran