24
votes

I'm trying to get td values of tr.. but unfortunately it's not working.. may be there is something wrong

My html looks like

<tr class="dname">
     <td>abc</td>
      <td>value here</td>
</tr>

My jquery code is

  jQuery(".dname").find("tr td:eq(1)").val();

What's wrong in this ?

5

5 Answers

50
votes

jQuery find() method returns the descendants of the selected element. You are already selecting the <tr> with a class of dname and then trying to find a descendant which is also a <tr>.

https://api.jquery.com/find/

The following should work:

jQuery(".dname").find("td:eq(1)").text();

Edit: text() instead of val() as @freedomn-m pointed out

11
votes

Replace n with child no.

$(".dname td:nth-child(n)").text();

For e.g. for 2nd child

$(".dname td:nth-child(2)").text();
4
votes

You're already filtering on the tr by its class name, so there's no need to find by tr again.

jQuery(".dname").find("td:eq(1)").text()

Also, you need to .text() to get the contents of a <td> not .val().

JSBin here.

Hope this helps :)

1
votes

Because that <td> is the last child of your <tr> you can access it like below,

jQuery(".dname > td:last-child").text();

1
votes

Just wanted to point out that if you want some particular value inserted in the cell then do the following (for example if you need to show the text TEST in the table cell):

$(".dname td:nth-child(n)").text("TEST");