Nithesh Narayanan
Nithesh Narayanan

Reputation: 11765

Selecting second cell of a row using jQuery

I have the following HTML table

<table>
<tr class="trSelected">
<td>One</td>
<td>two</td>
</tr>
</table>

I just want to get the text in the second column (ie,'two')

I tried

$('.trSelected td').eq(2).val()

but it returs an empty string How it is possible through jQuery?

Upvotes: 5

Views: 11997

Answers (5)

Powertieke
Powertieke

Reputation: 2408

List Indices start from 0, not from 1.

You are trying to select column 3, which does not exist. Also, the .val() method is only used for getting and setting form fields, not normal html elements. Use .text() instead!

$('.trSelected td').eq(1).text()

might work.

Upvotes: 4

Steve Claridge
Steve Claridge

Reputation: 11080

You could use the nth-child selector or you should use eq(1). Also, you should use .text() or .html() instead of .val()

An example in jsFiddle: http://jsfiddle.net/heTyW/

Upvotes: 0

Bertrand Marron
Bertrand Marron

Reputation: 22210

First for all, eq()'s argument is a 0-based index, so to get the second element, you'd need to call eq(1).

Secondly, the val() method is used to retrieve the value from inputs, you're dealing with td elements, not inputs.

$('.trSelected td').eq(1).text()

will do what you're expecting.

Upvotes: 2

samy
samy

Reputation: 14962

Use the nth-child selector to get the second cell

$(".trSelected td:nth-child(2)").val()

Upvotes: 3

Igor Dymov
Igor Dymov

Reputation: 16460

You should use the following construction:

$('.trSelected td').eq(1).text()

or

$('.trSelected td:eq(1)').text()

eq selector uses zero-based index. Also you have to use text method, not val.

Upvotes: 12

Related Questions