最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to get span in tr with jquery - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Jan 23, 2017 at 17:09 cucurucucuru 3,72811 gold badges47 silver badges86 bronze badges 2
  • jQuery Learning Center: link Selecting Elements by Attribute – Andreas Commented Jan 23, 2017 at 17:12
  • Do you want to set value of span attr or select the span with attr? Answer is relative to that. – Rahi Commented Jan 23, 2017 at 17:16
Add a ment  | 

5 Answers 5

Reset to default 2

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"]')

You can try the following:

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

Use

$('#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./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>

Try this:

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

评论列表(0)

  1. 暂无评论