Find td with specific text, and operate on the td right after that one?

前端 未结 6 660
逝去的感伤
逝去的感伤 2020-12-19 04:13

I\'m not very familiar with jQuery selectors, so would like some help.

I have a table like this:

相关标签:
6条回答
  • 2020-12-19 04:54

    My initial answer missed the point about updating the text, here is a sample with this included:

    $(".test td:contains(Heading 1)")
        .next().text(function(){
            return $(this).text() + " Hello"
        });
    

    I don't believe you can use the append method as I think it only works to add html tags.

    0 讨论(0)
  • 2020-12-19 04:57

    First, you want to use :contains:

    jQuery( "td:contains(text)" );
    

    Then, you can use .next and .append:

    jQuery( "td:contains(text)" ).next().append("Hello");
    

    Here's a working snippet to demonstrate usage:

    jQuery(function($) {
      $("td:contains(Text to Find)").next().append(" Hello");
    });
    table {
      border-collapse: collapse;
    }
    
    td {
      border: 1px solid #ccc;
      padding: 2px 5px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <table>
      <tbody>
        <tr>
          <td>Some Text</td>
          <td>More Text</td>
          <td>YMT</td>
        </tr>
        <tr>
          <td>Text to Find</td>
          <td>Modify:</td>
          <td>Do nothing here</td>
        </tr>
      </tbody>
    </table>

    0 讨论(0)
  • 2020-12-19 05:01

    This should work...

    $(function() {
        var searchText = "Section Heading 3";
        var output = "";
        $("td").each(function(i, item) {
            if($(item).html() == searchText) {
                output = $(item).html();
                output += $(item).closest("td").html()
            }
        });
    
        console.log(output);
    });
    

    Here's a jsFiddle http://jsfiddle.net/5ELLM/

    0 讨论(0)
  • 2020-12-19 05:03

    for information

    var data ="Search string" $('#table1 td:contains('+data+')').next().text();

    0 讨论(0)
  • 2020-12-19 05:17

    jQuery has :contains() pseudo class :

    $('td:contains("Section Heading 4")').next().text(function(_,t){
        return t + ' Hello';
    })
    

    Be carefull, :contains is case sensitive.

    0 讨论(0)
  • 2020-12-19 05:19
    var tds=$("table.test").find("td");
    var td,i;
    for(i=0;i<tds.size();i++) {
      td=tds.eq(i);
      if (td.text().indexOf("Section Heading 4")!=-1) {
        td.next().text(td.next().text()+"hello");
      }
    }
    
    0 讨论(0)
提交回复
热议问题