简体   繁体   中英

how to get span in tr with jquery

I have a table:

<table id="myTable">
    <tbody>
      <tr>
       <td><span data-mydata="data1">first value data1</span></td>
       <td><span data-mydata="data2">first value data2</span></td>
      </tr>
       <tr>
       <td><span data-mydata="data1">second value data1</span></td>
       <td><span data-mydata="data2">second value data2</span></td>
      </tr>
   </tbody>
 </table>

I want to change the span texts at the last tr with jquery, I got all the span in the row with:

$('#myTable tbody tr:last td span')

what I want is the span which attr data-mydata is equal to data2.

how can I do it?

Use attribute equals selector to select the element based on the attribute value.

 $('#myTable tbody tr:last td span[data-mydata="data2"]')

Use :nth-child instead of jQuery :last for making it more faster.

$('#myTable tbody tr:last-child td span[data-mydata="data2"]')

您可以尝试以下方法:

$('#myTable tbody tr:last span[data-mydata="data2"]').text('to whatever text you want.');

采用

$('#myTable').find('span[data-mydata="data2"]').text();

Use the last selector to get the last tr then use [attribute=value]

 $("tr:last span[data-mydata='data2']").css({"background": "gold"}) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="myTable"> <tbody> <tr> <td><span data-mydata="data1">first value data1</span></td> <td><span data-mydata="data2">first value data2</span></td> </tr> <tr> <td><span data-mydata="data1">second value data1</span></td> <td><span data-mydata="data2">second value data2</span></td> </tr> </tbody> </table> 

尝试这个:

$('#myTable tbody tr:last td span').attr('data-mydata','data2')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM