开发者

jquery selector - selecting the 2nd span child inside each table row

I have the following mark-up:

<table>
<thead>
...
</thead>
<tbody>
<tr>
    <td>
      <span class='select_me' id='42'></span>
    </td>
     <td>
      <span class='select_me' id='43'></span>
     </td>
  </tr>
 <tr>
    <td>
      <span class='select_me' id='50'></span&g开发者_JS百科t;
    </td>
     <td>
      <span class='select_me' id='54'></span>
     </td>
  </tr>
</table>

How would I go about selecting the 2nd or 1st span 'select_me' in each row? I figure it's something like this - I want to get the id

$("td").each(function(){
v = $(this).children(".select_me:first").attr("id");
});

but it outputs 'undefined', any help would be appreciated


You can use the :eq selector:

$("tr").each(function() {
    var firstId = $("span.select_me:eq(0)", this).attr("id");
    var secondId = $("span.select_me:eq(1)", this).attr("id");
});

Since you only have two <span> elements per row, you can also use the :first and :last selectors:

$("tr").each(function() {
    var firstId = $("span.select_me:first", this).attr("id");
    var secondId = $("span.select_me:last", this).attr("id");
});


For first -

$("tr").each(function(){
    v = $(this).find("td:nth-child(1) span.select_me").attr("id");  
});

For second -

$("tr").each(function(){
    v = $(this).find("td:nth-child(2) span.select_me").attr("id");  
});


try this -

 $("td").each(function(){
   first = $(this).find("span.select_me:eq(0)").attr("id");// for first 
   Second = $(this).find("span.select_me:eq(1)").attr("id");// for second 
    });


nth-child may help: http://api.jquery.com/nth-child-selector/

$("tr td:nth-child(2) span.select_me").attr('id')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜