Jquery get nth-child having a particular class

2019-08-04 19:05发布

I have a html table as follows

<table id = "table1">
<tr>
    <td class="take">1</td>
    <td>2</td>
    <td>3</td>
    <td class="take">4</td>
    <td>5</td>
    <td class="take">6</td>
</tr>
<tr>
    <td class="take">11</td>
    <td>12</td>
    <td>13</td>
    <td class="take">14</td>
    <td>15</td>
    <td class="take">16</td>
</tr>
</table>

I would like to get a jquery selector which gets me the second td having class of take in the first tr of table. :) funny huh? But it pains.

I tried below.

$("#table1").find('tr:first-child td.take:nth-child(2)').text()

But no use.

EDIT: I want td having text 4 not 2

I made a fiddle to play around.

Fiddle here

6条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-08-04 19:34

//alert("hello");
var tableRows = $("#table1").find("tr"); //fetching all rows of the tbody
//(tableRows);
$.each(tableRows, function(index, value) { //iterating all fetched rows
    //alert("hello");
    var tdValue = $(value).find("td:nth-child(3)").html();
    $(value).find("td:nth-child(3)").addClass("addclass");
});
.addclass {
  background: red;
}

table,
th,
td {
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<table id="table1">
  <tr>
    <td class="take">1</td>
    <td>2</td>
    <td>3</td>
    <td class="take">4</td>
    <td>5</td>
    <td class="take">6</td>
  </tr>
  <tr>
    <td class="take">11</td>
    <td>12</td>
    <td>13</td>
    <td class="take">14</td>
    <td>15</td>
    <td class="take">16</td>
  </tr>
</table>

var tableRows = $("#table1").find("tr"); //fetching all rows of the tbody
$.each(tableRows, function( index, value ) { //iterating all fetched rows
    var tdValue=$(value).find("td:nth-child(3)").html(); //can set which column required
    $(value).find("td:nth-child(3)").addClass("adding"); //can set anything
});
查看更多
forever°为你锁心
3楼-- · 2019-08-04 19:37

you can use direclly,using eq() selector

$("#table1 td.take:eq(1)").text();

DEMO

查看更多
做自己的国王
4楼-- · 2019-08-04 19:43

I would like to get a jquery selector which gets me the second td having class of take in the first tr of table

$("#table1 tr:first td.take:eq(1)").text()

Or,

$('#table1').find('tr:first td.take:eq(1)').text()
查看更多
Rolldiameter
5楼-- · 2019-08-04 19:44

Try this : You can iterate all tds with class="take" in first row of table and then check it's index eqaul to 1 (as index is 0 based, second element will have index =1).

$("#table1").find('tr:first-child td.take').each(function(index){

  if(index==1)
    alert("Text is "+$(this).text());
});

JSFiddle Demo

查看更多
何必那么认真
6楼-- · 2019-08-04 19:47

You can use :firstto target first row tr along with `:eq' selector with index 1 to target 2nd td element in it:

$("#table1").find('tr:first td.take:eq(1)').text();

Working Demo

查看更多
Animai°情兽
7楼-- · 2019-08-04 19:48

Try this

$("#table1").find("tr td.take:eq(1)").text();

FIDDLE

查看更多
登录 后发表回答