jQuery - find table row containing table cell containing specific text

前端 未结 5 1719
孤街浪徒
孤街浪徒 2020-12-07 22:21

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

相关标签:
5条回答
  • 2020-12-07 22:33

    You can use filter() to do that:

    var tableRow = $("td").filter(function() {
        return $(this).text() == "foo";
    }).closest("tr");
    
    0 讨论(0)
  • 2020-12-07 22:33
       <input type="text" id="text" name="search">
    <table id="table_data">
            <tr class="listR"><td>PHP</td></tr>
            <tr class="listR"><td>MySql</td></tr>
            <tr class="listR"><td>AJAX</td></tr>
            <tr class="listR"><td>jQuery</td></tr>
            <tr class="listR"><td>JavaScript</td></tr>
            <tr class="listR"><td>HTML</td></tr>
            <tr class="listR"><td>CSS</td></tr>
            <tr class="listR"><td>CSS3</td></tr>
    </table>
    
    $("#textbox").on('keyup',function(){
            var f = $(this).val();
          $("#table_data tr.listR").each(function(){
                if ($(this).text().search(new RegExp(f, "i")) < 0) {
                    $(this).fadeOut();
                 } else {
                     $(this).show();
                }
            });
        });
    

    Demo You can perform by search() method with use RegExp matching text

    0 讨论(0)
  • 2020-12-07 22:39
    $(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'.

    0 讨论(0)
  • 2020-12-07 22:45

    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();
     });
    
    0 讨论(0)
  • 2020-12-07 22:46

    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

    0 讨论(0)
提交回复
热议问题