Jquery get nth-child having a particular class

此生再无相见时 提交于 2020-01-05 14:03:12

问题


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


回答1:


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




回答2:


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()



回答3:


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




回答4:


Try this

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

FIDDLE




回答5:


you can use direclly,using eq() selector

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

DEMO




回答6:


//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
});


来源:https://stackoverflow.com/questions/27519457/jquery-get-nth-child-having-a-particular-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!