sdasdadas
sdasdadas

Reputation: 25096

Finding Table Within Table - JQuery

I am trying to find, using JQuery, the row and column number of a table cell. However, my tables are nested:

<table>
    <tr>
        <td>
            <table><tr><TD></TD></tr></table>
        <td>
            <table>...</table>
    </tr>
    <tr>
    ...
</table>

The td object that JQuery should act on is the on on the inner table. I have noted it with capitals in the above code.

I've seen some examples for single tables - is there a way to do this for nested ones as well?

EDIT:

That is to say, I am trying to find the row and column number of the OUTSIDE table, but the object being acted on is an INSIDE td element.

Upvotes: 2

Views: 3152

Answers (2)

Joseph Silber
Joseph Silber

Reputation: 219930

This will get you the parent td:

$('#inner-td').parent().closest('td');

Note: using just parent() will not work, since that only looks at the immediate parent. Using closest() on its own wouldn't work either, since it'll return the current td, because closest() looks for the closest element matching the passed selector, including the current element.

Upvotes: 3

techfoobar
techfoobar

Reputation: 66663

Check this fiddle: http://jsfiddle.net/pg4sj/

Code:

$('table table td').click(function() { // change this to suit your selector
    var theTD = $(this).parents('table:first').parents('td:first');
    var col = theTD.index() + 1;
    var row = theTD.parents('tr:first').index() + 1;
    alert('[Row, Col] => ['+row+', '+col+']');
});

Upvotes: 2

Related Questions