How to get data from the 5th cell in a html table row using jQuery

I have code that works fine:

var myValue = $(this).parents('tr:first').find('td:first').text();

is there anyway to get something like this working as the below code DOESN"T work:

var myValue2 = $(this).parents('tr:first').find('td:fifth').text();

as you can see I am trying to get the 5th column in the row.

2 Answers

Use :eq:

var myValue2 = $(this).parents('tr:first').find('td:eq(4)').text();

If $(this) refers to an element within the same row as the cells you are trying to select, you can shorten it slightly, using closest:

var myValue2 = $(this).closest('tr').find('td:eq(4)').text();

In jQuery, :first is a shortcut for :eq(0); there is no pseudo-class named :fifth. You might be able to do something like:

var myValue2 = $(this).parents('tr:first').find('td:nth-child(5)').text();

And I think you can combine the two:

var myValue3 = $(this).parents('tr:first td:nth-child(5)').text();

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like